I saw a presentation on cppcon of Piotr Padlewski saying that the following is undefined behaviour:
int test(Base* a){
int sum = 0;
sum += a->foo();
sum += a->foo();
return sum;
}
int Base::foo(){
new (this) Derived;
return 1;
}
Note: Assume sizeof(Base) == sizeof(Derived)
and foo
is virtual.
Obviously this is bad, but I'm interested in WHY it is UB. I do understand the UB on accessing a realloc
ed pointer but he says, that this is the same.
Related questions: Is `new (this) MyClass();` undefined behaviour after directly calling the destructor? where it says "ok if no exceptions"
Is it valid to directly call a (virtual) destructor? Where it says new (this) MyClass();
results in UB. (contrary to the above question)
C++ Is constructing object twice using placement new undefined behaviour? it says:
A program may end the lifetime of any object by reusing the storage which the object occupies or by explicitly calling the destructor for an object of a class type with a non-trivial destructor. For an object of a class type with a non-trivial destructor, the program is not required to call the destructor explicitly before the storage which the object occupies is reused or released; however, if there is no explicit call to the destructor or if a delete-expression (5.3.5) is not used to release the storage, the destructor shall not be implicitly called and any program that depends on the side effects produced by the destructor has undefined behavior.
which again sounds like it is ok.
I found another description of the placement new in Placement new and assignment of class with const member
If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object, if:
the storage for the new object exactly overlays the storage location which the original object occupied, and
the new object is of the same type as the original object (ignoring the top-level cv-qualifiers), and
the type of the original object is not const-qualified, and, if a class type, does not contain any non-static data member whose type is const-qualified or a reference type, and
the original object was a most derived object of type T and the new object is a most derived object of type T (that is, they are not base class subobjects).
This seems to explain the UB. But is really true?
Doesn't this mean, that I could not have a std::vector<Base>
? Because I assume due to its pre-allocation std::vector
must rely on placement-new
s and explicit ctors. And point 4 requires it to be the most-derived type which Base
clearly isn't.