Help returning a instance out of scope!

closed account (N1A5SL3A)
I am currently writing a custom string class that uses cstring to store the data. On top of that, I am writing operator overloads. Here is what I'm trying to perform:

jumboStr = (jumboStr + temp); //Combines strings: "bat" + "man" = "batman"

I believe my assignment function is correct, but in my + operator function, I am trying to return a dead instance. I'm stuck and would GREATLY appreciate some help. Thanks.

Here are my constructor, =, and + functions.

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
  CDString::CDString(char * ptr)
{
	cap = 20;
	end = 0;
	str = new char[cap];
	str[0] = '\0';
	while (str[end] = ptr[end])
		end++;
	createdCount++;
}

void CDString::operator = (const CDString& rValue)
{
	delete[] str;
	int x = rValue.cap;
	str = new char[x];
	cap = x;
	for (int i = 0; i <= rValue.end; i++)
		str[i] = rValue.str[i];
	end = rValue.end;
}

CDString& CDString::operator + (const CDString& rVal) const
{
	CDString tempStr;
	tempStr.end = end + rVal.end;

	tempStr.cap = cap + rVal.cap;
	//if ((tempStr.cap % end) >= 20)
	//	tempStr.cap = tempStr.cap - 20;

	delete[] tempStr.str;
	tempStr.str = new char[tempStr.cap];

	for (int x = 0; x < end+1; x++)
		tempStr.str[x] = str[x];

	int num1 = 0;
	for (int x = end; x < rVal.end; x++)
	{
		tempStr.str[x] = rVal.str[num1];
		num1++;
	}	

	return tempStr;
}
Remove the ampersand from the return type on line 23. Any time you have a function of the following form:
1
2
3
4
5
6
T &f(/*...*/){
    //...
    T some_name;
    //...
    return some_name;
}
you're almost certainly doing it wrong.
1
2
delete[] tempStr.str;
tempStr.str = new char[tempStr.cap];

If that new-expression throws an exception, your code will lose the user's data.

If you intend to implement operator +=:
1
2
3
4
5
6
7
8
9
10
T& operator+=(T const& other) {
  // add other to *this
  return *this;
}
// later (as a non-member)
T operator+ (T lhs, T const& other) 
{ return lhs += other; }
// or as a member
T operator+ (T const& other) 
{ T result = *this; return result += other; }
Last edited on
Topic archived. No new replies allowed.