Copy elision of overlapping objects

68 Views Asked by At

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?

1

There are 1 best solutions below

1
NathanOliver On

why can't it do the same for overlapping objects as well?

Because the size of the object would be wrong. In the case of

D() : C(f()) {} 

the sizeof(D) can be larger than sizeof(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

D(int) : D(g()) {}

You get the same thing in the other direction. If D is a base class of another object then eliding D(g()) would mean that the object that actually gets created is a D and not whatever inherited it and if it is larger than you are in trouble.