constructor from a string literal fails

I'm trying to create an custom array...but I'm having trouble with my constructor from a literal....if I compile without doing a call from a string literal it's fine, but if a do as you can see below it launch an error...anyone knows why?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
String(const std::string&& str){ //here is the problem
		size = str.length();
		ptr = new C [size];
		std::stringstream line(str);
		C unit;
		int cont = 0;
		while(line>>unit){
			ptr[cont] = unit;
			cont++;
		}
			ptr[cont] = '\0';
		
	}

	





1
2
3
4
5
6
7
8
9
10
11
	


int main(){
	
	String<char> my{"this is not working"};
	
	return 0;
}

	

You must allocate enough space for the terminating NUL character if you're going to use one.

length() function doesn't include the null terminated character?
this is my whole code....now you can have a better idea...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

#include <iostream>
#include <stdio.h>
#include <cstring>
//#include <sstream>

template<typename C>
class String{
private:
	static const int short_max = 15;
	int size;
	char* ptr;
	
public:
	String():size(0),ptr(nullptr){};
	String(int s){
		size(s);
		ptr = new C [s];
		for(int i = 0;i <=size;i++){
			ptr[i]= '\0';
		}
		
	}
	String(C& c){
		size(c.size);
		ptr = new C [c.size];
		for(int i = 0;i <=c.size;i++){
			ptr[i] = c.ptr[i];
		}
		
	}
	String(const std::string&& str){ //here is the problem
		size = str.length();
		ptr = new C [size];
		std::stringstream line(str);
		C unit;
		int cont = 0;
		while(line>>unit){
			ptr[cont] = unit;
			cont++;
		}
			ptr[cont] = '\0';
		
	}
	
	
	
	C& operator[](int n){return ptr[n];}
	
	String& operator+=(C c){
		size_t len = strlen(ptr);     
		ptr[len + 1] = c;
		return *this;
	}
	
};


int main(){
	
	String<char> my{"a"};
	
	return 0;
}
length() function doesn't include the null terminated character?

No, it does not.

Looking at the rest of your code, I think you could benefit from the reminder that valid indexes for an array of size n are 0 through n-1, because it doesn't observe this rule in quite a few places.

If your String class is templated on the character type, don't you think you should be using that type in your data members?

Topic archived. No new replies allowed.