lundi 2 octobre 2023

How does the compiler know to invoke move constructor when the return type of a function isn't rvalue reference? [duplicate]

Container::Container()
{
    std::cout << "CTOR called" << std::endl;
}

Container::Container(Container&& other)
{
    std::cout << "Move CTOR called" << std::endl;
}

and

Container getContainer() {
    Container a{};

    return std::move(a);
}

int main() {
    Container a = getContainer();
}

Whenever I compile/run this with MSVC I get the following result:

CTOR called
Move CTOR called

The return type of getContainer() is Container and not Container& or Container&&, and so whenever I inspect the value category of the expression getContainer() as describted here it yields prvalue, so Container a = getContainer(); means Container a = prvalue;, so how to does the compiler know to treat getContainer() as a xvalue and therefore invoking the move constructor?

Aucun commentaire:

Enregistrer un commentaire