mercredi 24 juin 2015

using std::move and on a class without copy constructor and operator

Here is my code:

#include <iostream>


class carl{
    public:
    int x;

    carl(int y):x(y){

    }


    carl(carl&& other)
    {
    std::cout<<" cons called?"<<std::endl;
    this->x = other.x;
    other.x = 0;
    }


    void operator=(carl&& other){
    std::cout<<"operator called?"<<std::endl;
    this->x = other.x;
    other.x = 0;
    }
};



void funct(carl&& get){
std::cout<<get.x<<std::endl;    
}


int main(int argc, char** argv) {
    carl c(2);
    funct(std::move(c));
    std::cout<<c.x<<std::endl;
    return 0;
}

Output:

2
2

If i remember, there is a special rule for special member function stating that, if a class declared a move constructor/operator then that class will not automatically generate copy operators/constructors.

Based from my example, it seems that move operators and constructors were not invoked but rather, it copied the value. It supposed to empty out the value of c' x and do the cout for confirms but none of that happened. can someone clarify what's happening with my code?

Aucun commentaire:

Enregistrer un commentaire