This question was triggered by confusion about RVO in C++11.
I have two ways to "return" value: return by value and return via reference parameter. If I don't consider the performance, I prefer the first one. Since return by value is more natural and I can easily distinguish the input and the output. But, if I consider the efficiency when return large data. I can't decide, because in C++11, there is RVO.
Here is my example code, these two codes do the same work:
return by value
struct SolutionType
{
vector<double> X;
vector<double> Y;
SolutionType(int N) : X(N),Y(N) { }
};
SolutionType firstReturnMethod(const double input1,
const double input2);
{
// Some work is here
SolutionType tmp_solution(N);
// since the name is too long, I make alias.
vector<double> &x = tmp_solution.X;
vector<double> &y = tmp_solution.Y;
for (...)
{
// some operation about x and y
// after that these two vectors become very large
}
return tmp_solution;
}
return via reference parameter
void secondReturnMethod(SolutionType& solution,
const double input1,
const double input2);
{
// Some work is here
// since the name is too long, I make alias.
vector<double> &x = solution.X;
vector<double> &y = solution.Y;
for (...)
{
// some operation about x and y
// after that these two vectors become very large
}
}
Here are my questions:
- How can I ensure that RVO is happened in C++11?
- If we are sure that RVO is happened, in nowadays C++ programming, which "return" method do you recommend? Why?
- Why there are some library use the return via reference parameter, code style or historical reason?
UPDATE Thanks to these answers, I know the first method is better in most way.
Here is some useful related links which help me understand this problem: