Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 723
Alon Amir Avatar asked Nov 02 '11 07:11

Alon Amir


2 Answers

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 :)

like image 154
larsmoa Avatar answered Oct 03 '22 14:10

larsmoa


Returning shared_ptr<vector<Foo>> guarantees no extra copy will occur.

Returning vector<Foo> may avoid extra copy if return value optimization (RVO) kicks in, or if move semantics from C++11 is used. But if it's important to avoid copy I wouldn't use this (even if you can ensure these optimizations will always be available), because I don't think it's a good idea to use return-a-copy semantics while actually meaning not copying.

I would probably go with one of these, but it depends:

  • pass a reference to vector<Foo> as parameter
  • pass insert iterator (e.g. back_inserter) instead
like image 37
hamstergene Avatar answered Oct 03 '22 15:10

hamstergene