3

Say I have the following:

Foo* foo = new Foo(bar);

//later on
*foo = Foo(anotherBar);

Since foo was allocated on the heap does this cause problems or will the memory from the temporary Foo be copied into the address of foo on the heap?

Thanks

jmasterx
  • 52,639
  • 96
  • 311
  • 557

5 Answers5

10

*foo = Foo(anotherBar); is no different than a regular assignment to an object of Foo type. *foo returns an lvalue of type Foo, and you are assigning to it.

Short answer: it won't cause problems, the temporary will be copied into the heap Foo object pointed by foo.

K-ballo
  • 80,396
  • 20
  • 159
  • 169
  • 9
    You still need to `delete foo` later on. And we're assuming `Foo`'s assignment operator is implemented correctly and frees any resources the original object may be managing. – Praetorian Sep 14 '11 at 01:45
  • ...or Foo overrides the new operator in a weird way or... or... or so many other things that should be considered in C++ – K-ballo Sep 14 '11 at 01:56
2

As long as you remember to delete foo at some point, that will not cause memory leaks.

Jeff Linahan
  • 3,775
  • 5
  • 37
  • 56
1

If Foo allocates anything on the heap, it won't be deallocated, as the first instance's destructor will not be called.

Matt K
  • 13,370
  • 2
  • 32
  • 51
  • Do you mean destructor instead of constructor? If it has a destructor the [C++ rule of three](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three/4172961#4172961) suggests it ought to also have an assignment operator too because of precisely that. – Flexo Sep 14 '11 at 14:30
  • bluh? yes, that's what i meant! – Matt K Sep 15 '11 at 00:47
1

If you can't be sure that the assignment operator will do the right thing, you could consider manual deletion and reconstruction without releasing the memory:

foo->~Foo();
foo = new (foo) Foo(anotherBar);

I would certainly not recommend this, and it's non-intuitive and inelegant, but I thought I put it out there just in case someone really wanted to avoid the deallocation and reallocation brought about by delete and a separate new.

Avoiding new altogether in favour of resource-managing containers is by far preferable, of course.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
-1

2 ojects are being created at runtime using the same pointer. When it points to 2nd memory location hence we have no way to access the first object inorder to free it back to heap, hence mem leak.

  • This is incorrect. The second object created is a temporary, *not* allocated via new. The first object is being dereferenced, so the assignment is not a pointer assignment. **The address the pointer points to does not get changed** – Flexo Sep 14 '11 at 14:17