繁体   English   中英

关于从 function 返回 unique_ptr 的问题

[英]Question about returning an unique_ptr from a function

根据文档,它说

我们已经在 return 语句中对局部值和 function 参数进行了隐式移动。 下面的代码编译得很好:

 std::unique_ptr<T> f(std::unique_ptr<T> ptr) { return ptr; }

但是,以下代码无法编译

std::unique_ptr<T> f(std::unique_ptr<T> && ptr) { return ptr; }

相反,您必须键入

std::unique_ptr<T> f(std::unique_ptr<T> && ptr) { return std::move(ptr); }

这是我的问题:

1.确实没有std::unique_ptr<T>的复制构造器,function 不应该接受声明为std::unique_ptr<T>的参数。 看到这个代码片段,它不编译。

#include <memory>

class FooImage{};

std::unique_ptr<FooImage> FoolFunc(std::unique_ptr<FooImage> foo)
{
    return foo;
}

int main()
{

    std::unique_ptr<FooImage> uniq_ptr(new FooImage);

    FoolFunc(uniq_ptr);
}

2.为什么

std::unique_ptr<T> f(std::unique_ptr<T> && ptr) {
    return ptr;
} 

不编译?

有人可以阐明这件事吗?

1.确实没有std::unique_ptr<T>的复制构造器,function 不应该接受声明为std::unique_ptr<T>的参数。

其实只要把原来的std::unique_ptr移到这个局部参数上就可以了

FoolFunc(std::move(uniq_ptr)); // ok
FoolFunc(std::unique_ptr<FooImage>{new FooImage}); // also ok

2.为什么

std::unique_ptr<T> f(std::unique_ptr<T> && ptr) { return ptr; }

不编译?

虽然ptr的类型是一个右值引用,但它本身是一个左值,所以return ptr会调用复制构造函数,你需要再次使用std::moveptr转换为右值

std::unique_ptr<T> f(std::unique_ptr<T> && ptr) { 
    return std::move(ptr); 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM