6

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.

user1899020
  • 13,167
  • 21
  • 79
  • 154
  • 6
    You need to do precisely nothing. It should work exactly as defined in your first example, without any user defined constructors or assignment operators. – Benjamin Lindley Aug 29 '13 at 21:44
  • 1
    You should follow The Rule of Zero and let the compiler generated the default move/copy assignment operators. – David G Aug 29 '13 at 21:45
  • 1
    You [don't need to define](http://coliru.stacked-crooked.com/view?id=b8e0d2214e) any constructors/assignment operators explicitly to get that to work. Refer to the [Rule of Zero](http://flamingdangerzone.com/cxx11/2012/08/15/rule-of-zero.html) for an explanation. – Praetorian Aug 29 '13 at 21:49
  • @BenjaminLindley Is this compiler dependent? If I do nothing, it cannot pass compilation in VC++ 2012. – user1899020 Aug 29 '13 at 22:23
  • 3
    @user1899020: it shouldn't be compiler dependent, but VC++ 2010 and 2012 have a serious bug where it refuses to compile this correctly. At this rate I'm afraid they won't fix it :( Your second block of code is _close_ to the easiest way to do it in VC++2012. Though VC++2013 will allow the simpler standard version. – Mooing Duck Aug 29 '13 at 22:25

1 Answers1

2

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.

Ivan
  • 2,007
  • 11
  • 15