![](/img/trans.png)
[英]Defaulted copy constructor and copy assignment assignment operator giving strange error
[英]Error using defaulted copy constructor: “deleted function”
我正在使用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;
^
我不知道從哪里開始診斷這個問題,因為我覺得復制構造函數存在並且不會被刪除。 可能是什么原因造成的?
正如juanchopanza所指出的,這是由於我的Factor
類中的一個不可復制的std::unique_ptr
數據成員導致復制構造函數被靜默刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.