Reputation: 12126
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?
Upvotes: 4
Views: 204
Reputation: 14093
It's called "placement new" and is usually used to construct an object in a specific memory location rather than the default returned by malloc
.
It's not supposed to be used this way (double construction) and the standard doesn't say what the behavior of using it this way will be.
That said, at least in the past. the global iostreams used to rely on this double construction. (But that still doesn't make it a good idea.)
Upvotes: 3
Reputation: 12983
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.
Upvotes: 6