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?
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 :)
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:
vector<Foo>
as parameterback_inserter
) insteadIf 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