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?
The implicitly-declared or defaulted default constructor for class T is undefined (until C++11)defined as deleted (since C++11) if any of the following is true: T has a member of reference type without a brace-or-equal initializer.
The copy constructor and copy-assignment operator are public but deleted. It is a compile-time error to define or call a deleted function. The intent is clear to anyone who understands =default and =delete . You don't have to understand the rules for automatic generation of special member functions.
The =delete is a new feature of C++0x. It means the compiler should immediately stop compiling and complain "this function is deleted" once the user use such function. If you see this error, you should check the function declaration for =delete . To know more about this new feature introduced in C++0x, check this out.
The default constructor creates the exact copy or shallow copy of the existing object. Thus, the pointer p of both the objects point to the same memory location.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With