“调用删除的函数的用法” std :: unique_ptr`移动构造函数?

问题描述 投票:0回答:1

[在定义采用对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;

我已经尝试通过将引用传递给自定义类来复制它,但是正如预期的那样,由于默认的move构造函数是由编译器隐式声明的,因此不会引起任何问题。为什么使用std::unique_ptr会发生这种情况? std::unique_ptr有一个默认的move构造函数,所以我想念什么?

c++ constructor smart-pointers move-semantics
1个回答
0
投票

您需要在arg中明确移动function2

std::unique_ptr<foo> foo(std::move (arg));
© www.soinside.com 2019 - 2024. All rights reserved.