这个问题是由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 …Run Code Online (Sandbox Code Playgroud) c++ return-value parameter-passing return-value-optimization c++11
我真的很担心在C++ 11中返回大数据.什么是最有效的方式?这是我的相关功能:
void numericMethod1(vector<double>& solution,
const double input);
void numericMethod2(pair<vector<double>,vector<double>>& solution1,
vector<double>& solution2,
const double input1,
const double input2);
Run Code Online (Sandbox Code Playgroud)
这是我使用它们的方式:
int main()
{
// apply numericMethod1
double input = 0;
vector<double> solution;
numericMethod1(solution, input);
// apply numericMethod2
double input1 = 1;
double input2 = 2;
pair<vector<double>,vector<double>> solution1;
vector<double> solution2;
numericMethod2(solution1, solution2, input1, input2);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
问题是,std :: move()在后面的实现中是无用的吗?
执行:
void numericMethod1(vector<double>& solution,
const double input)
{
vector<double> tmp_solution;
for (...)
{
// some operation about tmp_solution
// after that …Run Code Online (Sandbox Code Playgroud) 在https://doc.rust-lang.org/book/primitive-types.html#numeric-types中,它说在
设x = 42; // x的类型为i32
这意味着默认x类型i32.
但在http://rustbyexample.com/cast/literals.html中,它说明了这一点
未填充的文字,它们的类型取决于它们的使用方式
我知道我不能使用i32索引向量,但以下代码有效:
fn main() {
let v = vec![1, 2, 3, 4, 5];
let j = 1; // j has default type i32? or it has type when it is first used?
// And what is the type of 1?
println!("{}", v[1]); // is 1 a usize?
println!("{}", v[j]);
}
Run Code Online (Sandbox Code Playgroud)
那么,字面积分值的类型是什么?