Memory management question

The code I'm asking about is from a user-defined class called String. I want to be sure I'm not creating a memory leak.

1
2
3
4
5
6
7
8
9
10
String& String::operator+(const String& st) const
{
	char* st_added = new char[len + st.len + 1];
	st_added[0] = '\0';	//initialize st_added so strcat() works
	strcat(st_added, str);
	strcat(st_added, st.str);
	String* temp = new String(st_added);	//QUESTION HERE
	++num_strings; //static variable
	return *temp;
}

I know I can't create a String object and return a reference to it as the object ceases to exist after the call to the + operator, so I create a String* to label memory allocated by new and return what it points to. After the call to the + operator am I correct in assuming that the following happens:
1) the pointer temp ceases to exist
2) the memory allocated by new is temporarily labelled by the compiler
3) the String destructor is called after the return value is used. For string_1 = string_2 + string_3;
this would be after passing an argument to the overloaded = operator


If I'm wrong and the destructor is not called automatically then how am I supposed to overload the + operator so there is no leak?
first of all, operator+ is supposed to return a value, not a reference.

besides that, you have two memory leaks: the new'd char array (why is it new'd?) which is lost at the end of this function, and the new'd String (again, why is it new'd?), whose pointer is lost, although it could technically be recreated.

How am I supposed to overload the + operator so there is no leak?

don't use new
first of all, operator+ is supposed to return a value, not a reference.

Ah, that makes sense.
the new'd char array (why is it new'd?)

Because I like making hard to trace errors :(
1
2
3
4
5
6
7
8
9
String String::operator+(const String& st) const
{
	char st_added[len + st.len + 1];
	st_added[0] = '\0';	//initialize st_added so strcat() works
	strcat(st_added, str);
	strcat(st_added, st.str);
	++num_strings; //static variable
	return String(st_added);
}

Guess my questions are moot, but just to be sure I get what's going on the destructor is called automatically once the return value is used in the new code since it's a String value, correct?
Topic archived. No new replies allowed.