I have a very basic question in C++. How to avoid copy when returning an object ?
Here is an example :
std::vector test(const uns
Named Return Value Optimization will do the job for you since the compiler tries to eliminate redundant Copy constructor and Destructor calls while using it.
std::vector test(const unsigned int n){
std::vector x;
return x;
}
...
std::vector y;
y = test(10);
with return value optimization:
(in case you want to try it yourself for deeper understanding, look at this example of mine)
or even better, just like Matthieu M. pointed out, if you call test within the same line where y is declared, you can also avoid construction of redundant object and redundant assignment as well (x will be constructed within memory where y will be stored):
std::vector y = test(10);
check his answer for better understanding of that situation (you will also find out that this kind of optimization can not always be applied).
OR you could modify your code to pass the reference of vector to your function, which would be semantically more correct while avoiding copying:
void test(std::vector& x){
// use x.size() instead of n
// do something with x...
}
...
std::vector y;
test(y);