移动对象的知识点

《c++程序设计语言(第四版)》3.3.2章节、17.5.2章节

1、移动构造函数是构造函数的一种,用移动其他对象的资源的方式构造对象。

#define debug qDebug()<<

struct ceshi
{
    int frist;
    int second;
    ceshi(int one = 0,int two = 0):frist{one},second{two}
    {
    }

    ceshi(ceshi && c):frist{c.frist},second{c.second}
    {
        debug "调用移动构造";
        c.frist = -1;
        c.second = -1;
    }
};

int main(int argc, char *argv[])
{
    ceshi a(4,5);
    ceshi b = std::move(a);

    debug a.frist << a.second << &a;
    debug b.frist << b.second << &b;
}

2、std::move() 

此函数的作用只是获取右值引用,虽然函数名称叫做move,但没有移动任何东西。

    ceshi b = std::move(a);

这么写就会调用移动构造函数,将获取的右值引用作为参数传递。

3、如果类中没有定义移动构造函数,这么写会调用拷贝构造函数:

#define debug qDebug()<<
struct ceshi
{
    int frist;
    int second;
    ceshi(int one = 0,int two = 0):frist{one},second{two}
    {
    }

    ceshi(const ceshi & c)
    {
        this->frist = c.frist;
        this->second = c.second;
        debug "调用拷贝构造函数";
    }
};

int main(int argc, char *argv[])
{
    ceshi a(4,5);
    ceshi b = std::move(a);

    debug a.frist << a.second;
    debug b.frist << b.second;
}

猜你喜欢

转载自blog.csdn.net/kenfan1647/article/details/113790669
今日推荐