Do C++11 compilers turn local variables into rvalues when they can during code optimization?

前端 未结 4 791
余生分开走
余生分开走 2020-12-05 18:02

Sometimes it\'s wise to split complicated or long expressions into multiple steps, for example (the 2nd version isn\'t more clear, but it\'s just an example):



        
4条回答
  •  遥遥无期
    2020-12-05 18:19

    Be aware that besides move semantics that can greately speed up your code, compiler is also doing (N)RVO - (Named) Return Value Optimization, which can actually give even more efficiency to your code. I have tested your example and in g++4.8 it appears that your second example could be actually more optimal:

    object3 a(x);
    object2 b(a);
    object1 c(b);
    return c;
    

    From my experiments it looks like it would call constructor/destructor 8 times (1 ctr + 2 copy ctrs + 1 move ctr + 4 dtrs), compared to other method that call it 10 times (1 ctr + 4 move ctors + 5 dtors). But as user2079303 has commented, move constructors should still outperform copy constructors, also in this example all calls will be inlined so no function call overhead would take place.

    Copy/move elision is actually an exception to "as-if" rule, that means that sometimes you may be suprised that your constructor/destructor even tho with side effects does not get called.

    http://coliru.stacked-crooked.com/a/1ca7ebec0567e48f

    (you can disable (N)RVO with -fno-elide-constructors parameter)

    #include 
    #include 
    
    template
    struct A {
        A() { std::cout<<"A::A"<
        A(const A&) { std::cout<<"A::A&"<
        A(const A&&) { std::cout<<"A::A&&"< foo () {    
        A<2> a; A<1> b(a); A<0> c(b); return c;   // calls dtor/ctor 8 times
        //return A<0>(A<1>(A<2>()));  // calls dtor/ctor 10 times
    }
    int main()
    {
       A<0> a=foo();
       return 0;
    }
    

提交回复
热议问题