返回与使用参考参数 [英] Returning vs. using a reference parameter

查看:93
本文介绍了返回与使用参考参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



有时,我看到的函数是这样写的:

  int computeResult(); 

这是我习惯的。但是我看到他们这样写:

  void computeResult(int& result); 

我觉得这很奇怪。第二种方法比第一种方法有什么好处,如果有的话?

解决方案

这样的非const引用参数有两个常见的原因:




  • 您可能需要在函数中使用多个out参数,并且使用引用参数允许这样。 / p>


  • 复制对象可能很昂贵,因此您传递的引用将被改变,而不是返回可能被复制为返回的一部分的对象处理。昂贵的复制对象可以包括标准容器(例如向量)和管理堆内存的对象,其中将发生分配 - 复制 - 解除分配序列。请注意,编译器在可能的时候非常优化优化这些副本,因此这个原因比以前的导入更少。




编辑:我应该澄清,即使在C ++中,您使用单个内置类型引用参数提供的具体示例也非常典型。在这种情况下,返回值几乎总是优先的。


This is really bugging me, coming from a C# background.

Sometimes, I see functions written like this:

int computeResult();

This is what I'm used to. But then I see them written like this:

void computeResult(int &result);

I find this strange. What benefits does the second method have over the first, if any? There must be something, since I see it all the time.

解决方案

There are two common reasons for such non-const reference parameters:

  • You may need multiple "out" parameters in a function, and using reference parameter(s) allows for this.

  • Your object may be expensive to copy, and so you pass in a reference that will be mutated rather than returning an object that may get copied as part of the return process. Expensive-to-copy objects may include standard containers (like vector) and objects that manage heap memory where an allocation-copy-deallocate sequence would occur. Note that compilers are getting really good at optimizing away these copies when possible and so this reason has less import than it used to.

EDIT: I should clarify that even in C++ the specific example you've provided with a single builtin type reference parameter is pretty atypical. In such cases a return value is almost always preferred.

这篇关于返回与使用参考参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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