Reputation: 2139
I was told that the following code would result in a memory leak but I'm not certain why
object f(void)
{
object * o = new object(...);
return *o;
}
Is it because the object *o is copied before it is returned and the original copy is never deleted because it isn't an automatic variable?
Upvotes: 1
Views: 80
Reputation: 141544
The object created by new
is never delete
d.
The returned value is a separate object that is copy-constructed from the object pointed to by o
.
In general, a function T f(){ /*...*/ return y; }
creates its return value as if by T{y}
, i.e. constructing a T
with the argument y
.
Upvotes: 3