Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete object and create again at the same memory place

When I delete some object with the delete operator, and then create again with new operator, what is the guarantee that the object will be created at the same memory place?

Some example:

Object* obj = new Object(5);
delete obj;
Object* obj = new Object(2);
like image 353
Tom Avatar asked Dec 15 '22 07:12

Tom


1 Answers

what is the guarantee that the object will be created at the same memory place?

There are no such guarantees whatsoever.

However, you will sometimes see the next object created in the same place in memory under certian circumstances. In particular, in a MSVC Debug build you might see this happen frequently. But you should never rely on this behavior. It will stop happening just when you think it is working perfectly, and it never guaranteed to happen.

If you do need to create an object in the same place in memory, there is a C++ mechanism for that, called "placement new." However I must warn you -- using this is a bit tricky because you have to establish a buffer first, then placement-new your object there, and then explicitly call the destructor yourself before creating the next object. When you're done, you have to destroy the buffer. Not to mention alignment concerns, which complicates matters to a whole other level.

There are many opportunities for bugs and mistakes when using placement-new, the code can be difficult to maintain, and the times when you actually need this functionality is exceedingly rare in normal programming. As long as I've been doing C++ professionally, I could count the number of times I needed placement-new on one hand.

If you don't absolutely , positively know that you need placement-new, you don't need it.

like image 142
John Dibling Avatar answered Feb 04 '23 14:02

John Dibling