Reputation: 1057
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);
Upvotes: 4
Views: 1250
Reputation: 101456
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.
Upvotes: 6
Reputation: 918
You can't with new but you can if you want to manually assign it in memory, however not really practical. Here is more information: C++ Pointer: changing the contents without changing the address?
Upvotes: 1
Reputation: 6610
If you want to regenerate a project in teh memory space of the old object, look into memset
.
Upvotes: 0
Reputation: 234424
what is the guarantee that the object will be created at the same memory place?
None at all.
Upvotes: 5