mardi 24 mars 2020

Unexpected copy constructor

In the following example I am expecting only a single copy-construction, as I thought the intermediate copies would by copy elided. The only required (I thought?) copy would be in the constructor of B to initialize the member variable a.

#include <iostream>

struct A
{
    A() = default;
    A(A const&) { std::cout << "copying \n"; }
};

struct B
{
    B(A _a) : a(_a) {}
    A a;    
};

struct C : B
{
    C(A _a) : B(_a) {}
};

int main()
{
    A a{};
    C c(a);
}

When I execute this code (with -O3) I see the following output

copying 
copying 
copying 

Why aren't these intermediate copies elided?

Aucun commentaire:

Enregistrer un commentaire