C++ 中的函数按值返回还是按引用返回?
当一个函数(被调用者)返回一个数量给调用者函数时,它是由价值还是参考?
When a function (callee) returns a quantity to the caller function, is it returned by value or by reference?
问题是我编写了一个函数,它在调用时构建了一个非常大的向量.我想通过常量引用将这个大向量返回(在本例中为 main()
),以便我可以对其进行进一步处理.
The thing is I have written a function which builds a very large vector of when called. I want to return this big vector to the calling function , ( in this case main()
) by constant reference so I can do some further processing on it.
我很怀疑,因为有人告诉我,当 C++ 函数返回并终止时,与该函数关联的所有变量/内存都会被清除干净.
I was in doubt because I was told that when a C++ function returns and terminates, all the variables/memory associated with that function, get wiped clean.
struct node{
string key;
int pnum;
node* ptr;
}
vector< vector<node> > myfun1(/*Some arguments*/)
{
/*Build the vector of vectors. Call it V*/
return v;
}
int main(void)
{
a=myfun1(/* Some arguments */)
}
推荐答案
C++ 函数可以按值、按引用(但不通过引用返回局部变量)或按指针(再次,不返回本地指针).
C++ functions can return by value, by reference (but don't return a local variable by reference), or by pointer (again, don't return a local by pointer).
当按值返回时,编译器通常可以进行优化,使其与按引用返回一样快,而不会出现悬空引用的问题.这些优化通常称为返回值优化 (RVO)"和/或命名返回值优化 (NRVO)".
When returning by value, the compiler can often do optimizations that make it equally as fast as returning by reference, without the problem of dangling references. These optimizations are commonly called "Return Value Optimization (RVO)" and/or "Named Return Value Optimization (NRVO)".
另一种方法是调用者提供一个空向量(通过引用),并让函数填充它.然后它不需要返回任何东西.
Another way to for the caller to provide an empty vector (by reference), and have the function fill it in. Then it doesn't need to return anything.
您绝对应该阅读这篇博文:想要速度?按值传递.
You definitely should read this blog posting: Want Speed? Pass by value.
相关文章