"Use of deleted function" 调用 std::unique_ptr 移动构造函数时?

"Use of deleted function" when calling `std::unique_ptr` move constructor?

我在定义一个对 std::unique_ptr 对象进行移动引用的函数时遇到编译问题。

#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;

我试图通过传递对自定义 class 的引用来复制它,但正如预期的那样,它不会引起任何问题,因为编译器隐式声明了默认移动构造函数。为什么 std::unique_ptr 会发生这种情况? std::unique_ptr 有一个默认的移动构造函数,所以我缺少什么?

出于安全原因,施加了一些限制。命名变量永远不会被视为右值,即使它被声明为右值。要获得右值,应使用函数模板 std::move()。右值引用也只能在特定情况下修改,主要用于移动构造函数。

void function2(std::unique_ptr<foo>&& arg) {
    std::unique_ptr<foo> foo(std::move(arg));
}