移动构造函数

C++中对象发生拷贝的场景可以分为两种,一种是被拷贝的对象还要继续使用,另一种是被拷贝的对象不再使用;第二种一般可以认为是对右值的拷贝,也就是一个临时对象;

C++11中引入了移动构造函数,对象发生拷贝时不需要重新分配空间而是使用被拷贝对象的内存,即临时对象的内存,从而提高代码运行效率(作用)
 
class HasPtrMem 
{
public:
    HasPtrMem() : d(new int(3)) 
    {
        cout << "Construct: " << ++n_cstr << endl;
    }

    HasPtrMem(const HasPtrMem & h) : d(new int(*h.d)) 
    {
        cout << "Copy construct: " << ++n_cptr << endl;
    }

    HasPtrMem(HasPtrMem && h) : d(h.d)    // 移动构造函数
    { 
        h.d = nullptr;                  // 将临时值的指针成员置空
        cout << "Move construct: " << ++n_mvtr << endl;
    }

    ~HasPtrMem() 
    {
        delete d;
        cout << "Destruct: " << ++n_dstr << endl;
    }

    int * d;
    static int n_cstr;
    static int n_dstr;
    static int n_cptr;
    static int n_mvtr;
};
上例中的HasPtrMem (HasPtrMem &&)就是所谓的移动构造函数。与拷贝构造函数不同的是,移动构造函数接受一个所谓的“右值引用”的参数。可以看到,移动构造函数使用了参数h的成员d初始化了本对象的成员d(而不是像拷贝构造函数一样需要分配内存,然后将内容依次拷贝到新分配的内存中),而h的成员d随后被置为指针空值nullptr,这就完成了移动构造的全过程。
posted @ 2018-08-05 12:37  心媛意码  阅读(1312)  评论(0编辑  收藏  举报