It's very very horrible, yes, but there's not a guaranteed memory leak.
That depends on the type Foo
.
In practice there will never be a type where it's not a memory leak, but in principle one can define e.g.
struct Foo
{
std::unique_ptr<Foo> p;
void operator=( Foo& o ){ p.reset( &o ); }
};
I added the horrible incompatible-with-standard-containers void
result type, just for good measure. :)
So, regarding
” the memory allocated is leaked, as the pointer is lost. Is this true or am I missing something?
… you're ¹only missing the case of the trainee who copies the above code directly from this SO answer and inserts it in the company's Big Application™, for some inexplicable reason.
Notes:
¹ Martin Matilla writes in a comment on the question: “I suppose this kind of initialization comes from Java/C# programmers trying to create new objects, noticing the compiler does not allow them to do so as foo is an object not a pointer, and adding the * so the compiler is happy.”, which is another possibility.