C ++中的函数按值还是按引用返回? [英] Function in C++ returns by value or by reference?

查看:136
本文介绍了C ++中的函数按值还是按引用返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当函数(callee)向调用函数返回一个数量时,它是由
值还是引用返回?



写一个函数,构建一个非常大的向量的时候调用。我想通过常量引用返回这个大向量到调用函数(在这种情况下 main()),在上面。



我有疑问,因为有人告诉我,当一个C ++函数返回并终止时,所有与该函数关联的变量/内存都会被擦除。

  struct node {

string key;
int pnum;
node * ptr;
}

向量< vector< node> > myfun1(/ *一些参数* /)
{

/ *构建向量的向量。调用它V * /

return v;

}

int main(void)
{
a = myfun1(/ * Some arguments * /)
}

C ++函数可以通过引用返回值(但不返回)



当按值返回时,编译器通常可以进行优化使其等同于通过引用返回的速度,而没有悬空引用的问题。这些优化通常被称为返回值优化(RVO)和/或命名返回值优化(NRVO)。



另一种方式为调用者提供



你肯定应该阅读这篇博客文章:想要速度?按值传递。


When a function (callee) returns a quantity to the caller function, is it returned by value or by reference?

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.

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++ 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).

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 ++中的函数按值还是按引用返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆