When I have an object allocated not dinamically and I return it by value:
string get()
{
string str("hello");
return str;
}
There are chances to get memory leak? I make some examples:
int main(int argc, char** argv)
{
string str=get(); // case 1
get(); // case 2
string* ptr=&get(); // case 3
}
In which cases there’s a memory leak?
There are no memory leaks, but case 3 isn’t even vaguely valid.
The
get()function returns a copy of the string, possibly optimized, sincestd::stringis a class and not a pointer or anything else. It works, from the user’s point of view, roughly the same as returning anintfrom a function: a copy is created and returned, and stays valid outside of the function scope so as to allow assignment or use. Without that behavior, return values in general wouldn’t be possible.It applies to PODs and classes very similarly (although the class needs a copy constructor and such). You should be able to do this for almost any
stdclass, although the cost of making a copy will vary (it’s a bad idea to return astd::vector<BigClass>(1000), for example). Depending on settings, your compiler may be able to optimize the copy away through RVO.Case 1 uses that: the copy is assigned to
str, no memory leak, no problem. Pretty simple.Case 2 discards the copy, but still, no problems.
Case 3 will try to take the address of the temporary return value, which will quickly be destroyed by the compiler (due to being unused) and make
ptra hanging pointer. Any use ofptrafter the temporary is gone will cause undefined behavior, probably an access violation. Where and when the temporary will be destroyed will depend on your compiler, settings, and other things you can’t rely on.The correct form is 1 (although 2 is also valid, just not very useful).