lundi 23 juillet 2018

After move constructor is called it should return empty string

class B
{


public:
    B() {

    }
    double _d;
    int* _p;
    string _str;

public:
    B(B&& rhs) : _d(rhs._d), _p(rhs._p), _str(move(rhs._str))
    {
        rhs._p = nullptr;
        rhs._str.clear();
    }

    B& operator=(B&& rhs)
    {  
        delete _p;

        _d = rhs._d;
        _p = rhs._p;
        _str = move(rhs._str);
        rhs._p = nullptr;
        rhs._str.clear();

        return *this;
    }
};



int main()
{

    int a = 4;
    B b;
    b._d = 3;
    b._p = &a;
    b._str = "erind";

    B&& k = move(b);

    cout << b._str << endl;



    getchar();
    return 0;
}

Investigating how the move constructor and move assignment operator works I came into this example, when I try to output the value _str of b I expect it to be Null or "" but not still "erind". am I missing something here?

When I try to initialize the field members in the constructor then everything is all right and a "" is returned. Why is it the case when i initialize the field members outside the _str is not cleared?

Aucun commentaire:

Enregistrer un commentaire