【发布时间】:2016-05-12 13:15:04
【问题描述】:
这个问题是由对 C++11 中的 RVO 的混淆引发的。
我有两种“返回”值的方法:按值返回和通过引用参数返回。如果我不考虑性能,我更喜欢第一个。由于按值返回更自然,我可以轻松区分输入和输出。但是,如果我考虑返回大数据时的效率。我无法决定,因为在 C++11 中,有 RVO。
这是我的示例代码,这两个代码做同样的工作:
按价值返回
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;
}
通过参考参数返回
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
}
}
这是我的问题:
- 我如何确保 RVO 发生在 C++11 中?
- 如果我们确定发生了 RVO,在当今的 C++ 编程中,您推荐哪种“返回”方法?为什么?
- 为什么有些库使用通过引用参数、代码风格或历史原因返回?
更新 多亏了这些答案,我知道第一种方法在大多数情况下都更好。
这里有一些有用的相关链接可以帮助我理解这个问题:
【问题讨论】:
标签: c++ c++11 parameter-passing return-value return-value-optimization