Function in C++ returns by value or by reference?(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.
这篇关于C++ 中的函数按值返回还是按引用返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 中的函数按值返回还是按引用返回?


基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07