Is it possible to ensure copy elision?

前端 未结 3 1974
别跟我提以往
别跟我提以往 2021-01-18 03:58

Copy elision is a neat optimization technique and in some cases relying on copy elision can actually be faster than passing around references \"by hand\".

So, let\'s

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-18 04:40

    No.

    But you can write an equivalent, although completely unreadable, code:

    BigObj f()
    {
        BigObj x(g());
        x.someMethod();
        return x;
    }
    
    //...
    BigObj z = f();
    //...
    

    is translated (with copy elision) to:

    void f(BigObj* obj)
    {
        new(obj) BigObj(g());
        obj->someMethod();
    }
    
    //...
    char z[sizeof(BigObj)];
    f((BigObj*)&z[0]);
    //...
    ((BigObj*)&z[0])->~BigObj();
    

    But seriously, just write your code in such a way that the compiler can elide the copy. I.e. return only one object without branching:

    BigObj f()
    {
        BigObj x, y;
        // use x and y
        if(condition)
            return x;
        else
            return y;
        // cannot be elided
    }
    
    
    BigObj f()
    {
        if(condition)
        {
            BigObj x;
            return x;
        }
        else
        {
            BigObj y;
            return y;
        }
        // can be elided
    }
    

提交回复
热议问题