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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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::vectoryou could also return it by argument.If you really want to return
shared_ptr<vector<T>>, consider ifshared_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::vectorhas a move constructor that will guarantee that returning a localstd::vectorwon’t require expensive copy operations.Remember, don’t prematurely optimize 🙂