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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With