加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c 11 – 移动构造函数是否隐式地为成员变量工作?

发布时间:2020-12-16 10:43:13 所属栏目:百科 来源:网络整理
导读:为什么不这样:(vs2010)在类中移动向量? #include vectorclass MoveTest{public: std::vectorint m_things;};int _tmain(int argc,_TCHAR* argv[]){ MoveTest m; m.m_things.push_back(12); MoveTest m2 = std::move(m); // std::vector has been copied,no
为什么不这样:(vs2010)在类中移动向量?

#include <vector>

class MoveTest
{
public:
    std::vector<int> m_things;
};

int _tmain(int argc,_TCHAR* argv[])
{
    MoveTest m;
    m.m_things.push_back(12);

    MoveTest m2 = std::move(m);
    // std::vector has been copied,not moved

    return 0;
}

这是否意味着每个使用std :: vector(和其他可移动类)的类都应该有一个显式的移动构造函数和赋值?

解决方法

使用完全符合C 0x编译器,您的类将具有移动成员的隐式移动构造函数,以及隐式复制构造函数.在此示例中,将使用隐式移动构造函数.

但是,在委员会同意此规则之前,MSVC2010已经出现,因此您必须明确地编写移动构造函数.然后,您还需要定义默认构造函数和复制构造函数,并且可能还应该定义移动赋值和复制赋值以获得良好的度量:

class MoveTest
{
public:
    std::vector<int> m_things;

    MoveTest()
    {}

    MoveTest(MoveTest&& other):
        m_things(std::move(other.m_things))
    {}

    MoveTest(MoveTest const& other):
        m_things(other.m_things)
    {}

    MoveTest& operator=(MoveTest&& other)
    {
        MoveTest temp(std::move(other));
        std::swap(*this,temp);
        return *this;
    }

    MoveTest& operator=(MoveTest const& other)
    {
        if(&other!=this)
        {
            MoveTest temp(other);
            std::swap(*this,temp);
        }
        return *this;
    }

};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读