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
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
*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
.
As long as you remember to delete foo at some point, that will not cause memory leaks.
If Foo
allocates anything on the heap, it won't be deallocated, as the first instance's destructor will not be called.
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.
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.