I have a bunch of methods that return vector<int>
. They don't return a reference or a pointer to vector<int>
because the returned value is not a part of class' state, it is just generated on the fly depending on the method arguments.
I would like to avoid vector<int>
copy constructor being called when I invoke the method like this.
vector<int> result = myClass.GenerateVectorOfInt(/* params */);
// Do something with the result;
What is the best way to do it?
Would this be an acceptable way of doing that? Or are there any other better or more elegant solutions.
vector<int> result = std::move(myClass.GenerateVectorOfInt(/* params */));
You need not do anything special, the compiler is allowed to elide the copy where feasible. This is called "Return-Value Optimization" (RVO).
If RVO does not occur, C++11 forces the vector
to be moved into place, which is cheap, independent of its size. Usually this is 1 pointer and 2 integer assignments. So the vector will never be copied, the move is the worst case.
If for any reason RVO does not happen and a move is too expensive for your usecase (highly unlikely), there is nothing you can do without changing the function's signature; adding std::move
or something like this at call point will not help.
If 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