user1899020
user1899020

Reputation: 13575

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

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.

Upvotes: 7

Views: 2555

Answers (1)

Ivan
Ivan

Reputation: 2057

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.

Upvotes: 2

Related Questions