函数返回另一个函数的返回 [英] Function returning the return of another function
问题描述
如果我想调用 Bar()
而不是 Foo()
, Bar()
是否会给我返回副本(其他开销)是什么Foo()返回,还是返回 Foo()
放在临时堆栈上的同一对象?
If I want to call Bar()
instead of Foo()
, does Bar()
return me a copy (additional overhead) of what Foo() returns, or it returns the same object which Foo()
places on the temporary stack?
vector<int> Foo(){
vector<int> result;
result.push_back(1);
return result;
}
vector<int> Bar(){
return Foo();
}
推荐答案
两者都可能发生.但是,大多数编译器在进行优化后就不会立即进行复制.
Both may happen. However, most compiler will not do copy as soon as you optimize.
您的代码表明应该有副本.但是,允许编译器删除所有不会更改语义和程序的副本.
Your code indicate there should be a copy. However, the compiler is allowed to remove any copy that do not change the semantic and the program.
注意:这就是为什么您永远都不能拥有一个复制构造函数,该复制构造函数除了正确复制外什么也不做,因为您永远无法确定是否会真正完成复制.
Note: This is why you should NEVER have a copy constructor that does anything but copying correctly as you can never be sure if a copy will be actually done or not.
这篇关于函数返回另一个函数的返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!