[英]What happens in C++ if a function return value is passed to a function reference argument?
Let's consider two functions:让我们考虑两个函数:
//Test functions
Object MakeObj(){/* processsing */};
Object ChangeObj(const Object& obj){/* processsing */};
//Then execute
Object test_obj = ChangeObj(MakeObj());
Is the execution safe?执行安全吗?
Where is stored the 'Object' return value of the MakeObj()? MakeObj() 的“对象”返回值存储在哪里? Can I use a reference to that storage?
我可以使用对该存储的引用吗?
Or a temporary variable is necessary:或者需要一个临时变量:
Object MakeObj(){/* processsing */}; Object ChangeObj(const Object& obj){/* processsing */}; Object tmp_obj = MakeObj(); Object test_obj = ChangeObj(tmp_obj);
Is there any performance gain or it is exactly the same, if the code from point 3 gets changed:如果第 3 点的代码发生更改,是否有任何性能提升或完全相同:
Object MakeObj(){/* processsing */}; Object ChangeObj(Object obj){/* processsing */}; //No reference here, so 'Object' value is created. Object test_obj = ChangeObj(MakeObj());
Is there a way to use "move" to avoid coping a big Object?有没有办法使用“移动”来避免应对大 Object? Eg:
例如:
Object ChangeObj(Object&& obj){/* processsing */};
If yes, how it would look like?如果是,它会是什么样子?
What would be the fastest implementation (as less coping as possible) of those two functions above?上面这两个功能的最快实现(尽可能少的应对)是什么? Assumption: "Object MakeObj();"
假设:“对象 MakeObj();” declaration cannot be changed.
声明不能更改。
Execution is safe because const reference extends object lifetime (or here )执行是安全的,因为const 引用延长了 object 的生命周期(或此处)
The object itself is stored somewhere on the stack, but it will not be erased as long as the const reference exists( compare asm line 20(non-reference) and 25-27(const reference)) object 本身存储在堆栈的某个位置,但只要存在 const 引用就不会被擦除(比较asm 行 20(非引用)和 25-27(const 引用))
No. It isn't necessary.不,没有必要。
In the general case, the code from point 4 is faster, even if there was a move
(in the case of a vector
, optimization for 2-3 assignment operations size_t
)在一般情况下,即使有
move
,第 4 点的代码也会更快(在vector
的情况下,优化 2-3 赋值操作size_t
)
move
can only be applied in the code from point 3, and then it will look like move
只能在第 3 点的代码中应用,然后看起来像
Object MakeObj(){/* processsing */};
Object ChangeObj(Object&& obj){/* processsing */};
Object tmp_obj = MakeObj();
Object test_obj = ChangeObj(std::move(tmp_obj));
//here tmp_obj is no longer valid
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.