mardi 25 juin 2019

Why is copy constructor called instead of move constructor when returning lvalue?

Lets say I have the class MyClass with a correct move constructor and which copy constructor is deleted. Now I am returning this class via lvalue like this:

MyClass func()
{
    return MyClass();
}

In this case the move constructor gets called when returning the class object and everything works as expected.

Now lets say MyClass has an implementation of the << operator:

MyClass& operator<<(MyClass& target, const int& source);

When I change the code above:

MyClass func()
{
    return MyClass() << 5;
}

I get the compiler error, that the copy constructor cannot be accessed because it is deleted. But why is the copy constructor beeing used at all in this case?

Aucun commentaire:

Enregistrer un commentaire