简体   繁体   English

返回仅移动右值引用

[英]returning a move-only rvalue reference

In the following code: 在以下代码中:

#include <memory>

struct C {
    C() = default;
    C(C const&) = delete;
    C(C&&) = default;

    int a;
};

C foo(C&& c) {
    return c;
}

int main()
{
  auto c = foo(C{});
}

I get an error at the return statement of foo : 我在foo的return语句中出错:

Use of deleted function 'C::C(const C&)'". 

Why is trying to call the copy constructor? 为什么要尝试调用复制构造函数? Shouldn't it be using the move constructor since c is an rvalue reference? 不应该使用移动构造函数,因为c是右值引用? And even if not for that reason, shouldn't a return statement always call the move constructor since the value can no linger be used after the return ? 即使不是因为这个原因,不应该return语句总是调用移动构造函数,因为return后值不能继续使用?

Inside function foo , c , a named thing, is an lvalue. 内部函数fooc ,一个命名的东西,是一个左值。 To invoke the move constructor, you'd need to explicitly make it look like an rvalue 要调用移动构造函数,您需要明确地使其看起来像一个右值

return std::move(c);

As pointed out by juanchopanza c is an lvalue (since it has a name) so it will try to copy that. 正如juanchopanza所指出的, c是一个左值(因为它有一个名字)所以它会尝试复制它。 instead of having to call std::move in the return statement though you can leverage the fact the local objects and function parameters that were passed by value can be considered as rvalues in the return statement. 虽然您可以利用事实,但是通过值传递的本地对象和函数参数可以被视为return语句中的rvalues,而不必在return语句中调用std::move That lets you rewrite the function like 这让你可以重写这个功能

C foo(C c) {
    return c;
}

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

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