我在定义一个对 std::unique_ptr
对象进行 move 引用的函数时遇到编译问题。
#include <memory>
class foo {
public:
foo() { /* */ };
};
void function(foo&& arg) {
foo bar(arg);
}
void function2(std::unique_ptr<foo>&& arg){
std::unique_ptr<foo> foo(arg);
}
int main(int argc, char const *argv[]) {
foo A;
function(foo());
function2(std::unique_ptr<foo>(new foo));
return 0;
}
这导致:
test.cpp: In function ‘void function2(std::unique_ptr<foo>&&)’:
test.cpp:16:30: 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>]’
16 | std::unique_ptr<foo> foo(arg);
| ^
In file included from /usr/include/c++/9.3.0/memory:80,
from test.cpp:1:
/usr/include/c++/9.3.0/bits/unique_ptr.h:414:7: note: declared here
414 | unique_ptr(const unique_ptr&) = delete;
我试图通过传递对自定义类的引用来复制它,但正如预期的那样,它不会引起任何问题,因为默认 move 构造函数是由编译器隐式声明的。为什么 std::unique_ptr
会发生这种情况? std::unique_ptr
有一个默认的 move 构造函数,所以我错过了什么?
最佳答案
出于安全原因,施加了一些限制。命名变量永远不会被视为右值,即使它被声明为右值。要获取右值,应使用函数模板 std::move()
。右值引用也只能在特定情况下修改,主要用于 move 构造函数。
void function2(std::unique_ptr<foo>&& arg) {
std::unique_ptr<foo> foo(std::move(arg));
}
关于c++ - 调用"Use of deleted function"move 构造函数时为`std::unique_ptr`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61563235/