How to make a class with a member of unique_ptr work with std::move and std::swap?

走远了吗. 提交于 2020-01-02 04:06:07

问题


I have a class. It has a member of unique_ptr.

class A
{
    std::unique_ptr<int> m;
};

I hope it works with the following statements

A a;
A b;
a = std::move(b);
std::swap(a, b);

How to make it?

According to the comments, I have a question. Is this compiler dependent? If I do nothing, it cannot pass compilation in VC++ 2012.

I tried before

struct A
{
    A() {}

    A(A&& a)
    {
        mb = a.mb;
        ma = std::move(a.ma);
    }

    A& operator = (A&& a)
    {
        mb = a.mb;
        ma = std::move(a.ma);
        return *this;
    }

    unique_ptr<int> ma;
    int mb;
};

But not sure if this is the best and simplest way.


回答1:


Your first example is absolutely correct in C++11. But VC++ 2012 currently doesn't implement N3053. As a result, the compiler does not implicitly generate move constructor or assignment operator for you. So if you stuck with VC++ 2012 you need to implement them by yourself.



来源:https://stackoverflow.com/questions/18521413/how-to-make-a-class-with-a-member-of-unique-ptr-work-with-stdmove-and-stdswa

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!