Search code examples
c++dynamicheap-memorynew-operator

When to use *(new Foo)


So I read about the problem with having something like

Foo bar = *(new Foo());

because after bar is out of scope and gets deleted from the stack there is no way to clean up Foo() from the heap. Is there any practical use to it?


Solution

  • Foo& foo = *(new Foo);
    delete &foo;
    

    But don't do that. It will confuse future maintainers, and there's no good reason for it. Use a pointer.