c++ - 从函数返回的对象在不使用时是否仍然创建?

标签 c++ lifetime

考虑以下代码。当 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/

相关文章:

c++ - eclipse mars c/c++ 不会在 Windows 7 上构建

reference - 在 Vec 中混合引用的生命周期

string - 从 String 转换为具有不同生命周期的 &str

php - 如何使用php在linux上获取c++编译结果

c++ - 如何在C++中正确使用hash_set

c++ - 我如何告诉当前或即将在 poll() 中阻塞的线程执行某些操作?

c++ - 为底层容器不存储真实对象的迭代器重载 operator->

c# - 一段时间后是否重置静态变量

multithreading - 线程: how to remove static lifetime requirement [duplicate]

rust - 编译器建议我添加一个 'static lifetime because the parameter type may not live long enough, but I don' t think that's what I want