C ++编译器可以为const返回值执行RVO吗? [英] Can a C++ compiler perform RVO for a const return value?

查看:100
本文介绍了C ++编译器可以为const返回值执行RVO吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我具有该功能

#include <string>

std::string const foo()
{
    std::string s = "bar";
    return s;
}

int main()
{
    std::string t = foo();
}

编译器是否可以为<$ c $执行(命名)返回值优化c> t ,即使 s t 的类型都与由于 const -ness的差异而返回 foo 的类型?

Can a compiler perform (named) return-value optimization for t, even though the types of s and t are both different from the return type of foo due to the const-ness difference?

(如果C ++ 03和C ++ 11的答案不同,那么我肯定很想知道C ++ 03的答案。)

(If the answer is different for C++03 and C++11 then I'm definitely interested in knowing the C++03 answer.)

推荐答案

RVO优化无法打破 const 的承诺,因此没有问题:可以执行RVO。

There is no way for RVO optimization to break the promise of a const, so there's no problem: RVO can be performed.

但是,移动语义 const 。它有效地禁用了移动语义,即 T(T&)构造函数或移动赋值运算符的调用。因此,通常不要在返回值上使用 const

However, move semantics is affected by the const. It effectively disables move semantics, that is, calls of a T(T&&) constructor or move assignment operator. So in general, don't use const on a return value.

Scott Meyers最初建议 const 返回值,以进行更合理的编码。

Scott Meyers originally recommended const on return values, for more sane coding.

然后,Andrei Alexandrescu在其关于DDJ的Mojo文章中指出,此后,移动语义,最好禁止返回值使用 const ,而忽略Scott的早期建议。

Then Andrei Alexandrescu, in his Mojo article for DDJ, noted that henceforth, with move semantics, const on return values should better be banned, and Scott's earlier advice ignored.

现在,我再也不用花时间学习各种专用RVO缩写,例如NRVO等。主要原因是这些含义改变了到一半,最初在g ++编译器中具有某种自定义功能的含义。

Now I never bothered to learn the various specialized RVO acronyms, like NRVO and so on. And a main reason is that these changed meaning halfway through, originally having one meaning with some custom functionality in the g++ compiler. The terminology here is just a mess.

因此,如果我的术语是错误的,并且我真的应该使用其他首字母缩写,那么请随时进行更正! :-)

So, if my terminology's wrong and I should really have used some other acronym, then please feel free to correct! :-)

这篇关于C ++编译器可以为const返回值执行RVO吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆