Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RVO for complex user-defined types in C++

In an programming interview I had yesterday, one of the programs I had to write ended up having something like this:

struct Blob
{
    // basic field containing image blob statistics.
};

std::vector<Blob> find_blobs (const Image& ...)
{
    std::vector<Blob> blobs;
    // ...
    return blobs;
}

I'm familiar with return value optimization (RVO), so I just mentioned that returning the vector would not cause a copy on popular compilers (there is a single return statement as the last line, and no control paths can return another object in the code I wrote).

However, the interviewer told me that since Blob may be a complex user defined type (UDT), the compiler may not be able to perform RVO. He further added that returning a std::vector<Blob*> would increase the chances that the compiler would perform the copy elision.

To the best of my understanding, the capacity the compiler has of performing RVO are completely irrelevant of the type of object being returned, save for non-copyable objects, for which the compiler will (should?) reject the code even if the resulting code could compile without ever invoking the copy constructor.

So, was the interviewer right? Can a complex return type prevent the compiler from applying RVO?

like image 659
André Caron Avatar asked Apr 06 '12 19:04

André Caron


1 Answers

No, the types used should not affect the optimization.

The only reason I see to use pointers would be that they are cheaper to copy if the compiler fails the RVO. Not likely with the most popular compilers.

like image 65
Bo Persson Avatar answered Nov 02 '22 13:11

Bo Persson