Delete an object and create it again in the same memory location

When I delete an object using the delete operator and then create it again with the new operator, what is the guarantee that the object will be created in the same memory location?

Example:

 Object* obj = new Object(5); delete obj; Object* obj = new Object(2); 
+4
source share
4 answers

What is the guarantee that the object will be created with the same memory location?

There are no such guarantees.

However, you will sometimes see the following object created in the same place in memory, according to the certian conditions. In particular, in the MSVC Debug assembly, you may notice that this happens frequently. But you should never rely on this behavior. This will stop when you think that it is working perfectly and it will never be guaranteed.

If you need to create an object in the same place in memory, there is a C ++ mechanism for it, called placing a new one. "However, I must warn you - using this is a bit complicated because you need to create a buffer first and then place a new object there and then explicitly call the destructor just before creating the next object. When you are done, you need to destroy the buffer. Not to mention already about alignment problems, which complicates matters at a completely different level.

There are many possibilities for errors and errors when using a new placement, the code can be difficult to maintain, and the time when you really need this function is extremely rare in normal programming. As long as I am professionally engaged in C ++, I could count the number of times I needed placement - a new one on the one hand.

If you are not completely sure that you know that you need a new placement, you do not need it.

+6
source

What is the guarantee that the object will be created in the same memory location?

Not at all.

+5
source

You cannot with a new one, but you can if you want to manually assign it in memory, however this is not very practical. Here's some more info: C ++ Pointer: changing content without changing address?

+1
source

If you want to restore the project in the memory space of the old object, look at memset .

0
source

Source: https://habr.com/ru/post/1494970/


All Articles