返回值是否将通过 c++0x 中的右值引用传递?

发布于 2024-08-02 13:01:28 字数 349 浏览 5 评论 0原文

假设我有一个函数:

typedef std::vector<int> VecType;
VecType randomVector();

int processing()
{
    VecType v = randomVector();
    return std::accumulate(v.begin(), v.end(), 0);
}

C++0x 是否明确表示将从 randomVector 的返回值中避免虚假副本?或者编译器是否需要实现 RVO?在我看来,值 randomVector() 应该被视为右值,因此应该调用 v 的移动构造函数,但我不完全确定这是真的。

Let's say I have a function:

typedef std::vector<int> VecType;
VecType randomVector();

int processing()
{
    VecType v = randomVector();
    return std::accumulate(v.begin(), v.end(), 0);
}

Does C++0x specifically say the spurious copy will be averted from the return value of randomVector? Or would a compiler need to implement the RVO? It seems to me like the value randomVector() should be treated as an rvalue, and thus v's move constructor should be called, but I'm not completely sure this is true.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

明媚殇 2024-08-09 13:01:28

规则如下:

  • 如果编译器可以执行 RVO,则允许执行此操作,并且不进行任何复制和移动。
  • 否则,将采用适当的构造函数。

就像你说的,临时是一个右值,因此选择移动构造函数,因为 13.3.3.2/3 中的规则表明右值引用比左值更好地绑定到右值参考。因此,在决定使用移动构造函数还是复制构造函数时,重载决策将优先选择移动构造函数。

允许编译器执行RVO的规则写在12.8/15处。

The rule is the following

  • If the compiler can do RVO, then it is allowed to do it, and no copy and no move is made.
  • Otherwise, the appropriate constructor is taken.

Like you say, the temporary is an rvalue, and thus the move constructor is selected, because of a rule in 13.3.3.2/3, which says that a rvalue reference binds to an rvalue better than an lvalue reference. In deciding whether to use the move or the copy constructor, overload resolution will therefor prefer the move constructor.

The rule that the compiler is allowed to perform RVO is written at 12.8/15.

故事还在继续 2024-08-09 13:01:28

所有返回值都被视为右值,因此如果编译器在这种情况下没有实现 RVO,则必须使用移动构造函数而不是复制构造函数。

All return values are considered to be rvalues so if the compiler doesn't implement RVO on this case it must use the move constructor rather than the copy constructor.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文