vendredi 29 juillet 2016

rvalues with copy operator

Consider this simple class

class Foo
{
    public:
    Foo() = default;
    Foo(const Foo &) = default;
    Foo & operator=(const Foo & rhs)
    {
        return *this;
    }
    Foo & operator=(Foo && rhs) = delete; 
};

Foo getFoo()
{
    Foo f;
    return f;
}

int main()
{
    Foo f;
    Foo & rf = f;
    rf = getFoo();    // Use of deleted move assignment.
    return 0;   
}

When I compile the example above I get error: use of deleted function 'Foo& Foo::operator=(Foo&&)'

From the Copy Assignment:

If only the copy assignment is provided, all argument categories select it (as long as it takes its argument by value or as reference to const, since rvalues can bind to const references), which makes copy assignment the fallback for move assignment, when move is unavailable.

Why doesn't the compiler fallback to copy assignment when const lvalue reference can bind to rvalue and const Foo & f = getFoo(); works.

Compiler - gcc 4.7.2.

Aucun commentaire:

Enregistrer un commentaire