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.
source share