Gottfried
Gottfried

Reputation: 2139

Why does this code have a memory leak in C++

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

Answers (1)

M.M
M.M

Reputation: 141544

The object created by new is never deleted.

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

Related Questions