gpt4 book ai didi

c++ - 是否自动返回局部变量 xvalues

转载 作者:IT老高 更新时间:2023-10-28 22:02:39 27 4
gpt4 key购买 nike

根据我对此发表的评论:

passing std::vector to constructor and move semantics以下代码中是否需要std::move,以确保返回值是xvalue?

std::vector<string> buildVector()
{
std::vector<string> local;

// .... build a vector

return std::move(local);
}

据我了解,这是必需的。我经常看到在从函数返回 std::unique_ptr 时使用它,但是 GManNickG 发表了以下评论:

It is my understanding that in a return statement all local variables are automatically xvalues (expiring values) and will be moved, but I'm unsure if that only applies to the returned object itself. So OP should go ahead and put that in there until I'm more confident it shouldn't have to be. :)

谁能澄清 std::move 是否必要?

行为编译器是否依赖?

最佳答案

您可以保证在这种情况下 local 将作为右值返回。通常编译器会执行返回值优化,尽管在这甚至成为问题之前,你可能根本看不到任何实际 Action ,因为 local 对象将直接在调用站点构造。

6.6.3 ["The return statement"] (2)中的一个相关:

A copy or move operation associated with a return statement may be elided or considered as an rvalue for the purpose of overload resolution in selecting a constructor (12.8).

为了澄清,这就是说返回的对象可以从本地对象 move 构造(即使在实践中 RVO 将完全跳过这一步)。标准的规范部分是 12.8 [“复制和 move 类对象”] (31, 32),关于复制省略和右值(感谢@Mankarse!)。


这是一个愚蠢的例子:

#include <utility>

struct Foo
{
Foo() = default;
Foo(Foo const &) = delete;
Foo(Foo &&) = default;
};

Foo f(Foo & x)
{
Foo y;

// return x; // error: use of deleted function ‘Foo::Foo(const Foo&)’
return std::move(x); // OK
return std::move(y); // OK
return y; // OK (!!)
}

将此与返回实际的右值引用进行对比:

Foo && g()
{
Foo y;
// return y; // error: cannot bind ‘Foo’ lvalue to ‘Foo&&’
return std::move(y); // OK type-wise (but undefined behaviour, thanks @GMNG)
}

关于c++ - 是否自动返回局部变量 xvalues,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9963974/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com