When should RVO kick-in?

前端 未结 4 1813
我在风中等你
我在风中等你 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:20

    I don't know the full conditions, but I believe the fact that you are returning a parameter and not an instance created in the function is causing the problem in your example.

    For me, the following showed the same address for both:

    #include 
    #include 
    
    std::string foo()
    {
       std::string s("rvo!");
       std::cout << "address: " << (void *)(&s) << std::endl;
       return s;
    }
    
    int main()
    {
       const std::string s = foo();
       std::cout << "address: " << (void *)(&s) << std::endl;
       std::cout << s << std::endl;
       return 0;
    }
    

    Follow up to darid's comment

    The codepad about page documents that for it use's the -fno-elide-constructors for C++. The documentation for this option form the g++ man page state:

    The C++ standard allows an implementation to omit creating a temporary which is only used to initialize another object of the same type. Specifying this option disables that optimization, and forces G++ to call the copy constructor in all cases.

    On my machine, compiling with -fno-elide-constructors prevents RVO, but compiling without allows it.

提交回复
热议问题