Search code examples
c++boostvectorc++11shared-ptr

return vector<Foo> or shared_ptr<vector<Foo>>?


in a function, which "return" would be more appropriate?

A. vector<Foo> ?

B. shared_ptr<vector<Foor>> ?

In other words, which copy is less heavy, what would you do, and why?


Solution

  • I think returning shared_ptr<vector<T>> rarely is useful. I would only do this if several objects where to hold a shared vector that they could manipulate. To me this indicates a design flaw. A better alternative is probably to return by const reference. This avoids (a potentially expensive) copy operation, but does not allow the accessor to alter the vector.

    If you are returning a local std::vector you could also return it by argument.

    If you really want to return shared_ptr<vector<T>>, consider if shared_ptr<const vector<T>> would do the job (the vector can be inspected by many, but only manipulated by the owner).

    However A is generally more expensive than B, but return value optimizations often applies here. For C++11 std::vector has a move constructor that will guarantee that returning a local std::vector won't require expensive copy operations.

    Remember, don't prematurely optimize :)