I have the following code :
struct foo {};
void bar(foo *d) {
new(d) foo(*d);
}
Does the expression new(d) foo(*d)
leave the object pointed to by d
unchanged? More specifically, is the above true if the class foo
and all the objects contained recursively within it only have trivial copy constructors, then does new(d) foo(*d)
leave *d
unchanged? A situation in which that is not true could be, new
first zeroes out the memory before calling the copy constructor. Are there such clauses in the C++ language?
Edit : There are non-trivial reasons why someone would want to do this. Consider copying objects across address spaces, say, from CPU memory to GPU memory. One solution for that is to do a byte-by-byte of the object. This works in lot of cases. If the class has virtual methods, then the byte-by-byte copy copies the vtable pointer, which would then be pointing to some CPU memory. One can use the above expression new(d) foo(*d)
on the object to force the compiler to reset the vtable pointer.