vendredi 26 novembre 2021

Copy elision and move constructor

Consider the following definition of Person:

struct Person
{
    Person() { std::cout << "construct, "; }
    Person(const Person&) { std::cout << "copy\n"; }
    Person(Person&&) { std::cout << "move\n"; }
};

And 3 different functions to create a Person:

Person create1()
{
    std::cout << "create1: ";
    Person p1{};
    return p1;
}

Person create2()
{
    std::cout << "create2: ";
    if constexpr (true)
    {
        Person p1{};
        return p1;
    }
    else
    {
        Person p2{};
        return p2;
    }
}
    
Person create3()
{
    std::cout << "create3: ";
    if constexpr (true)
    {
        return Person{};
    }
    else
    {
        return Person{};
    }
}

Finally, I call the create functions as follows:

int main()
{
    Person p1 = create1();
    Person p2 = create2();
    Person p3 = create3();
    return 0;
}

The output is:

create1: construct
create2: construct, move
create3: construct

What bothers me is the output of create2. If in create1 and create3, the move constructor is not called, why is it called in create2?

I am using GCC 12.0.0.

Aucun commentaire:

Enregistrer un commentaire