0

Possible Duplicate:
Why does the use of 'new' cause memory leaks?

I was wondering if,

Foo bar = *(new Foo());

is okay to do, or am I wasting memory because I cannot delete the the data from the heap after assigning the value to bar.

Community
  • 1
  • 1
aspotic
  • 76
  • 4

2 Answers2

1

That's an instant memory leak because you lose the reference to it on the heap.

I have to ask though, why would you want to add work for yourself, when you can simply invoke the constructor on the stack.

pickypg
  • 22,034
  • 5
  • 72
  • 84
1

This works differently as you might expected:

  1. you create temporary on the heap which is never destroyed = memory leak

  2. you then create COPY of the temporary object on the stack.

So this approach gives you nothing.. Maybe you need smart pointer there?

Community
  • 1
  • 1
nogard
  • 9,432
  • 6
  • 33
  • 53