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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With