【问题标题】:Error using defaulted copy constructor: "deleted function"使用默认复制构造函数时出错:“已删除函数”
【发布时间】:2016-01-01 12:53:54
【问题描述】:

我正在使用g++ 5.1.0编译下面的C++14程序test.cpp:

#include <memory>

class Factor {
  public:
    Factor(const Factor&) = default;
    Factor(Factor&&) = default;
    Factor& operator=(const Factor&) = default;
    Factor& operator=(Factor&&) = default;
    Factor(int data) { 
      _data = std::make_unique<int>(data);
    }
    int* data() const { return _data.get(); }
  private:
    std::unique_ptr<int> _data;
};

class Node {
  public:
    Node(const Node& other) : _factor(other._factor) {
    }
  private:
    Factor _factor;
};

int main(int argc, char **argv) {
}

当我尝试编译时,出现以下错误:

test.cpp: In copy constructor ‘Node::Node(const Node&)’:
test.cpp:19:52: error: use of deleted function ‘Factor::Factor(const Factor&)’
     Node(const Node& other) : _factor(other._factor) {
                                                    ^
test.cpp:5:5: note: ‘Factor::Factor(const Factor&)’ is implicitly deleted because the default definition would be ill-formed:
     Factor(const Factor&) = default;
     ^
test.cpp:5:5: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(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 test.cpp:1:
/usr/include/c++/5/bits/unique_ptr.h:356:7: note: declared here
       unique_ptr(const unique_ptr&) = delete;
       ^

我不知道从哪里开始诊断这个问题,因为对我来说,复制构造函数存在并且没有被删除似乎相当明显。这可能是什么原因?

【问题讨论】:

  • 您可能有一个不可复制的数据成员。在您未显示的代码中。
  • 私人部分有什么?有没有 const 数据成员?
  • @Jake 只要问题重现,就继续逐步删减内容。如果它消失了,你就找到了有问题的部分,并且可以从中制作 mcve。
  • wtf 是这里所有的反对票???
  • @LightnessRacesinOrbit 我的第一个示例不符合MCVE 的要求,这让很多人感到困扰。

标签: c++ gcc default-constructor deleted-functions


【解决方案1】:

正如juanchopanza 所指出的,这是由于我的Factor 类中的不可复制的std::unique_ptr 数据成员导致复制构造函数被静默删除。

【讨论】:

    猜你喜欢
    • 2013-08-19
    • 1970-01-01
    • 2020-05-14
    • 2014-03-24
    • 2017-05-10
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    相关资源
    最近更新 更多