dimanche 8 octobre 2017

return by value calls copy ctor instead of move

why compiler calls copy ctor instead of move?

class Qwe {
public:
    int x=0;
    Qwe(int x) : x(x){}
    Qwe(const Qwe& q) {
        cout<<"copy ctor\n";
    }
    Qwe(Qwe&& q) {
        cout<<"move ctor\n";
    }    
};

Qwe foo(int x) {
    Qwe q=42;
    Qwe e=32;
    cout<<"return!!!\n";
    return q.x > x ? q : e;
}

int main(void)
{
    Qwe r = foo(50);
}

the result is:

return!!!
copy ctor

"return q.x > x ? q : e;" for to disable nrvo. When I add std::move method move is called but in "A Tour of C++" author said that move ctor must be called when it available. What have I done wrong?

Aucun commentaire:

Enregistrer un commentaire