读书人

C++11中move构造函数的写法,该怎么解决

发布时间: 2012-09-13 09:51:52 作者: rapoo

C++11中move构造函数的写法
我这样写标准吗?

C/C++ code
class A{private:    char * p;public:    A()    {        p = new char[3];    }    ~A()    {        delete[] p;    }    A(A&& right)    {        auto p = this->p;        this->p = right.p;        right.p = p;    }};


[解决办法]
直接初始化列表里面解决
[解决办法]
operator的move语义用swap即可
[解决办法]
记得要实现 A(const A&& right)
比如下面的例子
C/C++ code
    using namespace std;    void test(const int& _data)    {        cout<<"not rVaue"<<endl;    }    void test(int&& _data)    {        cout<<"rVaue"<<endl;    }    void test(const int&& _data)    {        cout<<"const rVaue"<<endl;    }    int fun()    {        int i = 0;        return i;    }int main(){    const int i = 1;    test(fun());    test(i);    test(move(i));//此处不实现void test(const int&& _data)                  //就会进入void test(const int& _data)                  //而不是 void test(int&& _data)    return 0;}
[解决办法]
探讨

这个A(const A&&right)负责什么啊
比如A(A&& right)负责交换两个对象维护的资源。

读书人网 >C++

热点推荐