Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

unique-ptr

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.

like image 739
user1899020 Avatar asked Aug 29 '13 21:08

user1899020


1 Answers

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.

like image 58
Ivan Grynko Avatar answered Oct 24 '22 01:10

Ivan Grynko