Return value optimizations and side-effects

前端 未结 4 900
孤城傲影
孤城傲影 2020-12-23 22:51

Return value optimization (RVO) is an optimization technique involving copy elision, which eliminates the temporary object created to hold a function\'s return value in cert

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-23 23:31

    It states it pretty clear, doesn't it? It allows to omit ctor with side effects. So you should never have side effects in ctors or if you insist, you should use techniques which eliminate (N)RVO. As to the second I believe it prohibits NRVO since std::move produces T&& and not T which would be candidate for NRVO(RVO) because std::move removes name and NRVO requires it(thanks to @DyP comment).

    Just tested the following code on MSVC:

    #include 
    
    class A
    {
    public:
        A()
        {
            std::cout << "Ctor\n";
        }
        A(const A&)
        {
            std::cout << "Copy ctor\n";
        }
        A(A&&)
        {
            std::cout << "Move\n";
        }
    
    };
    
    A foo()
    {
        A a;
        return a;
    }
    
    int main() 
    {
        A a = foo();
        return 0;
    }
    

    it produces Ctor, so we have lost side effects for move ctor. And if you add std::move to foo() you will have NRVO eliminated.

提交回复
热议问题