I recently ran into an unusual use of the new operator to re-initialise a C++ class, the code is as follows:
#include <iostream>
struct Test { Test() { std::cout<<"Test Ctor\n"; } };
int main()
{
Test t ;
new (&t) Test;
return 0 ;
}
If this code is run, the Test ctor is called twice. In this case it appears that the 'new' operator is using the pointer to the object as the source of the memory rather than allocating new memory, valgrind comfirms no memory leaks.
Can someone shed some light on this use of the 'new' operator?
This operator is called placement new. It runs the constructor of the object at the given addresss without prior memory allocation. It could be used when allocating a large array first, then constructing many object on it, for instance.
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