关于从函数返回 unique_ptr 的问题
根据文档,说
我们已经对本地价值观和功能进行了隐式移动 返回语句中的参数。以下代码仅编译 很好:
std::unique_ptr
; f(std::unique_ptr ptr) { 返回指针; } 但是,以下代码无法编译
std::unique_ptr
; f(std::unique_ptr && ptr) { 返回指针; } 相反,您必须输入
std::unique_ptr
; f(std::unique_ptr && ptr) { 返回 std::move(ptr); }
以下是我的问题:
1.确实没有 std::unique_ptr
的复制构造函数,不应该有一个函数可以接受声明为 std::unique_ptr
的参数。请参阅此代码片段,它无法编译。
#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;
}
不能编译?
有人可以解释一下这个问题吗?
As per the document, which says that
We already have implicit moves for local values and function
parameters in a return statement. The following code compiles just
fine:std::unique_ptr<T> f(std::unique_ptr<T> ptr) { return ptr; }
However, the following code does not compile
std::unique_ptr<T> f(std::unique_ptr<T> && ptr) { return ptr; }
Instead, you must type
std::unique_ptr<T> f(std::unique_ptr<T> && ptr) { return std::move(ptr); }
Here are my questions:
1.There is no copy ctor for std::unique_ptr<T>
indeed, there should not a function could accept a parameter declared as std::unique_ptr<T>
. See this code snippet, it does not compile.
#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.why
std::unique_ptr<T> f(std::unique_ptr<T> && ptr) {
return ptr;
}
does not compile?
Could somebody shed some light on this matter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
其实只要把原来的
std::unique_ptr
移到这个本地参数就可以了虽然
ptr
的类型是右值引用,但它本身是一个左值,因此return ptr
会调用复制构造函数,您需要使用std::move
再次将ptr
转换为右值In fact, this is ok as long as you move the original
std::unique_ptr
to this local parameterAlthough the type of
ptr
is an rvalue reference, it is itself an lvalue, soreturn ptr
will call the copy ctor, you need to usestd::move
to castptr
to an rvalue again