两者之间有什么区别吗?
vector<int> function(vector<int>& input) {
// do something with input then return it
input.push_back(3);
return input;
}
Run Code Online (Sandbox Code Playgroud)
和
vector<int>& function(vector<int>& input) {
// do something with input then return it
input.push_back(3);
return input;
}
Run Code Online (Sandbox Code Playgroud)
有关系吗?因为当您将函数的返回值分配给新变量时,矢量会被复制:
vector<int>result = function(some_vector);
Run Code Online (Sandbox Code Playgroud)
有区别,第二个函数可以在语句中充当左值.
function(some_vector).push_back(4);
Run Code Online (Sandbox Code Playgroud)
这里不复制向量,修改原始的'some_vector'.此外,性能方面,这可能会产生很大的不同.