Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

avoid vector copy constructor

Tags:

c++

stl

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 */));
like image 809
mk33 Avatar asked Mar 15 '23 07:03

mk33


1 Answers

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.

like image 121
Baum mit Augen Avatar answered Mar 29 '23 16:03

Baum mit Augen