5

The compiler reminds me that I'm using a deleted function . https://ideone.com/3YAIlA

#include <memory>
using namespace std;
class foo
{
public:
    unique_ptr<int> p;
    ~foo()
    {

    }
};
int main()
{
    foo a, b;
    a = move(b);
    return 0;
}

compilation info

prog.cpp: In function 'int main()':
prog.cpp:15:4: error: use of deleted function 'foo& foo::operator=(const foo&)'
  a = move(b);


prog.cpp:3:7: note: 'foo& foo::operator=(const foo&)' is implicitly deleted because the default definition would be ill-formed:
 class foo


prog.cpp:3:7: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>& std::unique_ptr<_Tp, _Dp>::operator=(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]'

In file included from /usr/include/c++/5/memory:81:0,
                 from prog.cpp:1:


/usr/include/c++/5/bits/unique_ptr.h:357:19: note: declared here
       unique_ptr& operator=(const unique_ptr&) = delete;

If I remove the destructor ,my code compiles fine. https://ideone.com/UFB18P

iouvxz
  • 89
  • 9
  • 27
  • I understand that it cannot be copied, but the move constructor? Hmmm – Arnav Borborah Sep 10 '16 at 14:48
  • The chart in this answer is a good summary of the rules for when and what the compiler does for you regarding special members: http://stackoverflow.com/a/38687106/576911 – Howard Hinnant Sep 10 '16 at 15:01
  • If you *really* need a destructor for the class, it is very unlikely that the default move operations will do the right thing. Like if you have a raw pointer and need to delete it in the destructor. – Bo Persson Sep 10 '16 at 15:27

1 Answers1

6

Because that's what the standard says. When you start adding special member functions, you inhibit the automatic generation of some of the other ones. This is in the same category of rules as how writing a non-default constructor means a default one won't be automatically generated for you.

Add this:

foo& operator=(foo&&) = default;
Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055