Reputation: 125
Im getting a warning when I compile my code.. The warning is: reference to local variable 'str' returned [enabled by default] I don't whats the problem or what I'm doing wrong.. This is my code...
MyString& operator+(MyString &a){
char *tmp=new char[strlen(szArr)+strlen(a.szArr)+1];
strcpy(tmp, szArr);
strcat(tmp, a.szArr);
MyString str(tmp);
delete tmp;
return str;
}
MyString& operator+(char *s){
if(s)
return *this;
char *tmp=new char[strlen(szArr)+strlen(s)+1];
strcpy(tmp, szArr);
strcat(tmp, s);
MyString str(tmp);
delete tmp;
return str;
}
In both Im getting this warning.. I don't know why is complaining that Im returning the object..
Upvotes: 1
Views: 1181
Reputation: 4569
Another suggestion: you could use the operator form with two function parameters and keep the return-by-reference.
Have a look here for an example
Upvotes: 0
Reputation: 14174
The error is exactly what the compiler is telling you: You are returning a reference to a local variable. Local variables are stored at the stack, and when the function ends its local variables go out of scope, so returning a reference to a local variable has undefined behaviour.
You have to use return by value.
Upvotes: 0
Reputation: 3974
You are creating a temporary MyString str(tmp);
variable inside your function, and then you are trying to return a reference to the memory of that variable, which has gone out of scope.
I'm not sure that this is the exact reason for your error message, but it is a problem you will have whenever you try to use that return value for anything.
Upvotes: 0
Reputation: 168958
If you are returning a new object rather than one that already exists, you should not be returning a reference. Remove the reference token. (The object you have constructed will be destructed when the function returns, so the reference will target an invalid object. Returning a non-reference means that the object will be copied/moved instead, which is what you want. Optimizing compilers will elide the copy anyway.)
Also, since you don't modify the arguments, they should be declared const
so that const
objects (or string literals) can be passed in.
MyString& operator+(MyString &a);
MyString& operator+(char *s);
Should be:
MyString operator+(MyString const &a);
MyString operator+(char const *s);
Note that this logic is backwards:
if(s)
return *this;
This will no-op if the string is not null. I presume that you meant this:
if(!s)
return *this;
Upvotes: 1
Reputation: 6039
You are returning a reference to a local (stack) variable that will be out of scope when the function returns. The object will be invalid so the compiler is warning you not to do this.
Make sure you have defined a copy constructor and return the object by value (remove the &
from the return type).
Upvotes: 3