开发者

Does this cause memory problems?

开发者 https://www.devze.com 2023-04-04 12:25 出处:网络
Say I have the following: Foo* foo = new Foo(bar); //later on *foo = Foo(anotherBar); Since foo was allocated on 开发者_JAVA百科the heap does this cause problems or will the memory from the tempor

Say I have the following:

Foo* foo = new Foo(bar);

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

Since foo was allocated on 开发者_JAVA百科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 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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消