Returning a vector, is RVO or a move constructor being applied here?

327 Views Asked by At

I have a class, which has a std::vector data member. I then have a simple get member function which simply returns the data member by value.

class X{
    public:
    vector<shared_ptr<MyClass>> z;

    vector<shared_ptr<MyClass>> X::getVector(){
        return z;
    }
};

When I call the following C++:

std::vector<boost::shared_ptr<MyClass>> my_vec = obj->getVector();

this x86 is produced:

std::vector<boost::shared_ptr<MyClass>> my_vec = obj->getVector();
mov         rdx,qword ptr [r8+20h]  
test        rdx,rdx  
je          boost::boost::+3DCh (013F0F690Ch)  
lea         rcx,[x]  
call        std::vector<boost::shared_ptr<MyClass>, std::allocator<boost::shared_ptr<MyClass> > >::vector (013F0E9700h)  

I am expecting either return-value optimization (RVO) to be applied, or the std::vector move constructor. However, I am unable to deduce which from the x86?

2

There are 2 best solutions below

1
On

RVO is really a very basic and old optimization for compiler even since cfront. The compiler will try to construct the object in place if possible, and get rid of any copy/move. In your case, it is same as:

std::vector<boost::shared_ptr<MyClass>> my_vec(obj->z);

If you want to make sure no extra copy/move is invoked, just reutrn a reference from getVector();

2
On

No, a member is never automatically moved. That would unexpectedly invalidate this.

The member z is copied to a temporary, which is then either moved or RVO is applied. Since you only see one constructor call, it looks like RVO.