When will a C++11 compiler make RVO and NRVO outperform move semantics and const reference binding?

后端 未结 3 1935
轮回少年
轮回少年 2020-12-30 04:20

Consider the case when \"whole\" objects with move semantics enabled are returned from functions, as with std::basic_string<>:

std::wstrin         


        
相关标签:
3条回答
  • 2020-12-30 04:27

    I'm not sure if this is standardized (as Nicol says, all optimizations are up to the compiler), but I heard STL talk about this and (at least in MSVC), RVO happens before anything else. So if there's a chance to apply RVO, then that'll happen without any action on your part. Second, when you return a temporary, you don't have to write std::move (I think this is actually in the standard), since the return value will implicitly be treated as an rvalue.

    The upshot is: Don't second-guess the compiler, just write the most natural-looking code and it'll give you the best-possible result.

    0 讨论(0)
  • 2020-12-30 04:28

    What scheme is there to make a deterministic choice of these options, if any?

    There isn't one, and there never will be.

    Compilers are not required to do optimizations of any kind. The only thing you can do for certain is compile some code and see what comes out the other end.

    The most you will eventually get is a general heuristic, a community consensus where people say, "for most compilers, X seems to work fastest." But that's about it. And that will take years as compilers get up to speed with C++0x and implementations mature.

    0 讨论(0)
  • 2020-12-30 04:49

    std::move(build_report()) is wholly unnecessary: build_report() is already an rvalue expression (it is a call of a function that returns an object by value), so the std::wstring move constructor will be used if it has one (it does).

    Plus, when you return a local variable, it gets moved if it is of a type that has a move constructor, so no copies will be made, period.

    There shouldn't be any functional difference between declaring report as an object or as a const-reference; in both cases you end up with an object (either the named report object or an unnamed object to which the report reference can be bound).

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