【发布时间】:2020-07-14 05:23:53
【问题描述】:
对于现代 C++,我有点菜鸟。
手头的问题是,我想通过变量将 unique_ptr 传递给 ctor。
一切都很好,如果我直接传递unique_ptr,但是一旦我将它分配给一个变量,我就会得到一个编译错误:
test.cpp:25:22: 错误:使用已删除的函数‘std::unique_ptr<_tp _dp>::unique_ptr(const std::unique_ptr<_tp _dp>&) [with _Tp = Foo; _Dp = std::default_delete]'
#include <memory>
class Foo {
public:
Foo(void) {;}
};
class Bar {
public:
Bar(std::unique_ptr<Foo> x)
: m_foo(std::move(x))
{ ; }
std::unique_ptr<Foo> m_foo;
};
void test(void) {
auto bar0 = Bar(std::make_unique<Foo>()); // this works
auto foo = std::make_unique<Foo>(); // this works
auto bar1 = Bar(foo); // this FAILS
}
和
$ g++ --version
g++ (Debian 9.3.0-8) 9.3.0
$ g++ -c test.cpp -o test.o
test.cpp: In function ‘void test()’:
test.cpp:21:22: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Foo; _Dp = std::default_delete<Foo>]’
21 | auto bar1 = Bar(foo);
| ^
In file included from /usr/include/c++/9/memory:80,
from test.cpp:1:
/usr/include/c++/9/bits/unique_ptr.h:414:7: note: declared here
414 | unique_ptr(const unique_ptr&) = delete;
| ^~~~~~~~~~
test.cpp:10:28: note: initializing argument 1 of ‘Bar::Bar(std::unique_ptr<Foo>)’
10 | Bar(std::unique_ptr<Foo> x)
| ~~~~~~~~~~~~~~~~~~~~~^
make: *** [<builtin>: test] Error 1
为什么?
我正在调试的实际代码(并使用新的编译器进行编译)类似于:
auto x = function_creating_a_uniqptr(args,...); // might return NULL
if (pi == nullptr) {
return std::make_unique<Plugin>(); // Invalid plug-in
}
return std::make_unique<Plugin>(x);
【问题讨论】:
标签: c++ parameter-passing unique-ptr