c++ - 调用"Use of deleted function"move 构造函数时为`std::unique_ptr`?

标签 c++ constructor smart-pointers move-semantics

我在定义一个对 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/

相关文章:

phpbrew 5.3.10 构建错误 : dereferencing pointer to incomplete type

c++ - 多态性和引用切片

c++ - 错误变量 protected

c++ - 关于转换构造函数和赋值运算符

rust - 为什么 std::rc::Rc<> 不是 Copy?

c++ - 具有动态分配大小和预定大小的简单数组内存分配

java - 如何在不通过java中的 super 构造函数设置的情况下将消息设置为自定义异常类

c++ - 将一个类的static const数据成员初始化为一个类

c++ - 共享指针 : pointer to pointer

c++ - 不同的智能指针可以引用同一个对象吗?