When should RVO kick-in?

前端 未结 4 1841
我在风中等你
我在风中等你 2021-01-02 14:46

From the following code, If RVO has happened, I expect to see the 2 addresses pointing to the same location, however this is not the case (my compiler is MS VC9.0)



        
4条回答
  •  无人及你
    2021-01-02 15:22

    RVO generally applies when you return an unnamed temporary, but not if you return a previously created object.

    std::string foo() {
      return std::string("hello world"); // RVO
    }
    
    std::string foo() {
      std::string str("hello world");
      bar();
      return str; // Not RVO
    }
    
    std::string foo(std::string str) {
      return str; // Not RVO
    }
    

    A more general version is NRVO (Named return value optimization), which also works on named variables.

    std::string foo() {
      std::string str("hello world");
      bar();
      return str; // NRVO
    }
    
    std::string foo(std::string str) {
      return str; // Not NRVO, as far as I know. The string is constructed outside the function itself, and that construction may be elided by the compiler for other reasons.
    }
    
    std::string foo(std::string str) {
      std::string ret;
      swap(ret, str);
      return ret; // NRVO. We're returning the named variable created in the function
    }
    

提交回复
热议问题