c++referencecopy-constructortemporary-objects

Does the compiler perform return value optimisation in case of returning member variable?


Given the following code

class foo
{
    private:
        boost::shared_ptr <std::deque<foo> > m_ptr;
    public:
        foo();
        boost::shared_ptr <std::deque<foo> > get_my_ptr()
        {
            return m_ptr;
        }
};

And when we call get_my_ptr() function like this

boost::shared_ptr <std::deque<foo> > ptr = get_my_ptr()

Does the compiler call copy constructor to create ptr object or it can perform nrvo? And what is the difference we we call it like this

const boost::shared_ptr <std::deque<foo> >& ptr = get_my_ptr()

Solution

  • With NRVO, the compiler is allowed to omit copy- and move-construction if the return statement's expression is the name of a local, non-volatile object with automatic storage duration, which is not a function parameter. That local object is constructed directly in the storage where the function's return value would otherwise be copied to. These conditions are not met for member variables. I's only possible if you created a local copy of the member:

    boost::shared_ptr<std::deque<foo>> get_my_ptr()
    {
        auto p = m_ptr;
        return p;
    }
    

    In your example the copy ctor will be called, which will increase the reference counter of the shared pointer. The same will happen if you bind the returned object to a const reference.