Reference: Copy Elision
This can only apply when the object being initialized is known not to be a potentially-overlapping subobject:
struct C { /* ... */ };
C f();
struct D;
D g();
struct D : C
{
D() : C(f()) {} // no elision when initializing a base-class subobject
D(int) : D(g()) {} // no elision because the D object being initialized might
// be a base-class subobject of some other class
};
If the compiler can make out the memory layout of a non-overlapping object (such as of a primary data type) to elide copy and instead construct the object at its destination, why can't it do the same for overlapping objects as well? What is the limitation at the system level that would make it not possible for the compiler to do such copy elision?
Because the size of the object would be wrong. In the case of
the
sizeof(D)can be larger thansizeof(C)and if it is then you can't elide the base class as then there is no room for the derived part in the elided base object.With
You get the same thing in the other direction. If
Dis a base class of another object then elidingD(g())would mean that the object that actually gets created is aDand not whatever inherited it and if it is larger than you are in trouble.