C ++为什么在我的类中添加析构函数会使我的类无法移动?

时间:2016-09-10 14:42:28

标签: c++ grammar move-semantics

编译器提醒我,我使用了删除的功能。 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;
}

汇编信息

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;

如果我删除了析构函数,我的代码编译得很好。 https://ideone.com/UFB18P

1 个答案:

答案 0 :(得分:6)

因为that's what the standard says。当您开始添加特殊成员函数时,您将禁止自动生成其他一些函数。这与规则类别相同,如何编写非默认构造函数意味着不会为您自动生成默认构造函数。

添加:

foo& operator=(foo&&) = default;