Can a C++ compiler perform RVO for a const return value?

后端 未结 1 517
-上瘾入骨i
-上瘾入骨i 2020-12-11 02:34

Let\'s say I have the function

#include 

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

int main()
{
    std::string          


        
相关标签:
1条回答
  • 2020-12-11 02:46

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


    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 originally recommended const on return values, for more sane coding.

    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.


    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! :-)

    0 讨论(0)
提交回复
热议问题