Search code examples
c++visual-studio-2008stdvectorrvo

Is it a bad idea to return an object by value that contains a member vector?


Short version:

If my object contains a std::vector, do the same rules of thumb apply to returning that object by value as to returning the vector by value?

Does this change in C++11, which I understand "guarantees" returning a vector by value is fast?

Long version:

I have a small wrapper class that contains a std::vector.

class gf255_poly
{
    public:

        // ... Lots of polynomial methods

    protected:
        std::vector<unsigned char> p;
};

I'd like to return instances of this class from certain functions such as:

// Performs polynomial addition in GF(2^8). 
gf255_poly gf255_poly_add(const gf255_poly &poly1, const gf255_poly &poly2) const
{
    // Initialize:
    gf255_poly dst = poly1;

    // Add all coefficients of poly1 to poly2, respecting degree (the usual polynomial addition)
    for (int deg = 0; deg <= poly2.degree(); deg++)
        dst.addAt(deg, poly2.coef(deg));

    return dst;
}

I've found plenty of information on how to return a member vector and whether it is still a bad design pattern to return a std::vector (it seems that that's fine under most circumstances). I haven't found much that includes vectors that are members of larger objects, though.

Does the same advice apply? Do I need to do anything special in my copy constructor to help ensure return value optimization?

Are the answers to this question different for different versions of the C++ standard?


Solution

  • Your writing gf255_poly dst = poly1; followed by return dst; is exploiting Named Returned Value Optimisation (NRVO).

    This is a more recent innovation than Returned Value Optimisation but is certainly implemented by modern compilers, irrespective of the C++ standard they are targeting. To be absolutely clear, NRVO is not a C++11 specific thing.

    Exploiting NRVO is not a bad design choice as using it makes source code easier to read and maintain.