我看到了这个question,但并不能真正解决我的问题。
以下是我的课程,我想从初始化列表中初始化unique_ptr向量:
class MyClass
{
public:
vector<unique_ptr<int>> vec2;
MyClass();
};
MyClass::MyClass() :
vec2{
move(make_unique<int>(30)), // Doesn't work
move(make_unique<int>(20))} // Doesn't work
{
unique_ptr<int> myPtr= make_unique<int>(30); // this works
unique_ptr<int> myPtr2= make_unique<int>(20); // this works
vec2.push_back(move(myPtr)); // this works
vec2.push_back(move(myPtr2)); // this works
}
以下是错误:
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>]’
{ ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/7/memory:80:0,
from test.cpp:3:
/usr/include/c++/7/bits/unique_ptr.h:388:7: note: declared here
unique_ptr(const unique_ptr&) = delete;
我所知道的是,在调用move
时将调用move构造函数,我的意思是unique_ptr(const unique_ptr&&)
而不是unique_ptr(const unique_ptr&)
,所以为什么在错误消息中说unique_ptr(const unique_ptr&) = delete;
< / p>