【问题标题】:C++ Why adding a destructor to my class makes my class unmovable?C++ 为什么向我的类添加析构函数会使我的类不可移动?
【发布时间】:2017-01-18 12:34:53
【问题描述】:

编译器提醒我正在使用已删除的函数。 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

【问题讨论】:

  • 我知道不能复制,但是move构造函数呢?嗯
  • 这个答案中的图表很好地总结了编译器何时以及为你做什么关于特殊成员的规则:stackoverflow.com/a/38687106/576911
  • 如果你真的需要一个类的析构函数,默认的移动操作不太可能做正确的事情。就像你有一个原始指针并且需要在析构函数中删除它一样。

标签: c++ grammar move-semantics


【解决方案1】:

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

添加这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 2018-06-05
    • 2021-10-07
    • 2013-09-30
    • 2019-09-04
    • 1970-01-01
    • 2014-07-16
    相关资源
    最近更新 更多