Error using defaulted copy constructor: "deleted function"
Asked Answered
S

1

7

I am using g++ 5.1.0 to compile the following C++14 program 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) {
}

When I try to compile I get the following errors:

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;
       ^

I don't know where to begin diagnosing this issue because it seems fairly obvious to me that the copy constructor exists and is not deleted. What could be the cause of this?

Stylograph answered 4/10, 2015 at 22:7 Comment(7)
You probably have a data member that is not copyable. In code you haven't shown.Schaffel
What's in private section ? Is there any const data members ?Besse
@BaummitAugen I couldn't create a minimal example because I can't post the whole program and I wasn't sure what to cut out and what to leave in. Hence the post asking for help.Stylograph
@Stylograph Just keep cutting out stuff step by step as long as the problem is reproduced. If it goes away, you found the offending piece and can make the mcve from that.Parsee
wtf is with all the downvotes here???Minardi
@LightnessRacesinOrbit My first example didn't adhere to the MCVE requirement and this bothered a number of people.Stylograph
Oh yes so it didn't. You should know better after five years!!!Minardi
S
8

As juanchopanza indicated, this was due to a non-copyable std::unique_ptr data member in my Factor class which resulted in the copy constructor being silently deleted.

Stylograph answered 4/10, 2015 at 22:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.