Say I have the following code in a C++ program:
Object a = Object(someParameters);
new (&a) Object(someOtherParameters);
My assumption is that it replaces the contents of a with Object(someOtherParameters), avoiding a possible operator= declared for Object. Is this correct?
It’s called placement new. It calles the constructor on the specified memory rather than allocating new memory. Note that in this case you have to explicitly call the destructor of your object before freeing the allocated memory.
Clarification. Suppose you have allocated some raw memory
and you want to construct an object on that memory. You call
Now, before freeing the memory
you will have to call the derstuctor of Object explicitly
In your particular example, however, the potential problem is that you haven’t properly destroyed the existing object before constructing a new one in its memory.
Bonus:
Ever wondered how standard
std::vectorcan do without its contained objects being default-constructible? The reason is that on most, if not all, implementationsallocator<T>does not store aT* pwhich would require T to be default-constructible in case ofp = new T[N]. Instead it stores acharpointer – raw memory, and allocatesp = new char[N*sizeof(T)]. When youpush_backan object, it just calls the copy constructor with placement new on the appropriate address in that char array.