stl数据结构的输出参数效率与堆栈上的返回值的关系 [英] Efficiency of output parameter vs return value on the stack for stl data structures

查看:79
本文介绍了stl数据结构的输出参数效率与堆栈上的返回值的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我说我有功能

std::Vector<Point> calculate() {
   std::Vector<Point> points; //do stuff with points
   return points;
}

void calculate(std::Vector<Point>& points) {
   //do stuff with points
}

所以我的问题特定于在堆栈上初始化的对象,它们是stl对象。性能上有什么区别吗?什么是流行的方法

So my question is specific to objects initialized on the stack, and are stl objects. Is there any difference in performance, and what is the popular method of doing it

问候

推荐答案

将值用作参考参数具有以下属性:

Taking the value as a reference parameter has the following properties:


  1. 不进行复制,移动或任何其他操作

  2. 返回值不能立即在用户侧丢弃。他们不能只是临时使用您函数的参考参数或其他东西。他们必须声明一个变量,因此必须给它一个将在当前范围内使用的名称。

  3. API 建议该值是输入/输出参数。也就是说,传递了一个值,该值将被读取和写入。如果不是这种情况,则使用它表示次优的API设计元素。

  1. No copying, moving, or any other operation will be done.
  2. The return value cannot be immediately discarded on the user's side. They can't just shove a temporary at your function's reference parameter or something. They must declare a variable, and therefore they must give it a name which will live within the current scope.
  3. The API suggests that the value is an input/output parameter. That is, there is a value being passed in which will be read and written. If that is not the case, then using it represents a sub-optimal API design element.

返回值具有以下属性:

Returning the value has the following properties:


  1. 如果复制省略不可用(由于函数实现的性质,编译器不佳或返回值不正确)初始化一个新值),则返回值将被移动 。未复制。移动不是免费的,但是通常它并不比几个指针副本贵得多。

  2. API 强制值的输出性质。用户无法播放它传入的输出,因为它没有传入任何内容。类似地,该函数也无法读取任何值,因为它没有任何输入。它是一个输出价值,时期函数会生成并返回它。

  3. 可以根据用户的意愿立即丢弃返回值。显然,如果用户经常执行此操作,则表明存在某些问题,但是由用户决定是否要保留输出值。

  1. If copy elision is not available (either due to the nature of the function's implementation, a poor compiler, or that the return value is not initializing a new value), then the return value will be moved. Not copied. Movement is not free, but generally it is not much more expensive than a few pointer copies. No new objects or memory will be allocated or deallocated.
  2. The API enforces the output nature of the value. There is no way for the user to play with the output it passes in because it doesn't pass anything in. Similarly, there is no way for the function to read any values because it doesn't take anything in. It is an output value, period; the function generates it and returns it.
  3. The return value can be discarded immediately at the user's descretion. Obviously if users are doing this a lot, it suggests that something is wrong, but it is up to the user to decide if they want to keep the output value or not.

这篇关于stl数据结构的输出参数效率与堆栈上的返回值的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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