2014-03-03 160 views
-1

返回一个对象VS引用返回一个对象

vector<int> function(vector<int>& input) { 
    // do something with input then return it 
    input.push_back(3); 
    return input; 
} 

vector<int>& function(vector<int>& input) { 
    // do something with input then return it 
    input.push_back(3); 
    return input; 
} 

任何区别什么关系呢?当您分配功能到一个新的变量回归以来,矢量被复制反正:

vector<int>result = function(some_vector); 
+0

是的,它会被复制,但是如果你不想拷贝vector,比如'function(input).function ...' – songyuanyao

回答

6

是有区别的,第二个功能可以作为在一份声明中左值行事。

function(some_vector).push_back(4); 

这里不复制矢量,原来的'some_vector'被修改。另外,性能方面,这可能会产生很大的差异。

0

使用参考作为参数允许以使功能无效

void function(vector<int>& input) { 
    // do something with input then return it 
    input.push_back(3); 
    return input; 
} 

通过std::vector类的方式成员函数push_back的返回类型返回类型void

返回对向量的引用允许将函数调用与类std :: vector的其他方法链接在一起。例如:

function(v).push_back(value);