考虑以下代码。当 doStuff() 被调用但没有使用返回值时会发生什么? SomeClass 是否仍然创建?当然,创建本身可能会产生重要的副作用,但是复制构造函数也可以,并且它们在 RVO/复制省略中仍然被省略。
SomeClass doStuff(){
//...do stuff
return SomeClass( /**/);
}
SomeClass some_object = doStuff();
doStuff(); //What happens here?
(编辑:用 GCC -O3 对此进行了测试。对象被构造然后立即销毁)
最佳答案
我觉得对 RVO 和复制省略存在误解。这并不意味着没有创建函数的返回值。它总是被创建的,这不是实现可以逃避的事情。
在删除拷贝方面,唯一的余地是削减中间人,尽管有副作用。当您使用调用结果初始化对象时,标准允许插入目标对象,以便函数直接初始化。
如果您不提供目标对象(通过使用结果),则必须将临时对象物化并销毁,作为包含函数调用的完整表达式的一部分。
所以用你的例子来玩一下:
doStuff(); // An object is created and destroyed as part of temporary materialization
// Depending on the compilers analysis under the as-if rule, there may be
// further optimization which gets rid of it all. But there is an object there
// formally.
std::rand() && (doStuff(), std::rand());
// Depending on the result of std::rand(), this may or may not create an object.
// If the left sub-expression evaluates to a falsy value, no result object is materialized.
// Otherwise, one is materialized before the second call to std::rand() and
// destroyed after it.
关于c++ - 从函数返回的对象在不使用时是否仍然创建?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48782639/