函数调用中的C ++临时对象的生存期 [英] C++ temporary objects lifetime in a function call

查看:79
本文介绍了函数调用中的C ++临时对象的生存期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们将由临时智能指针管理的对象通过原始指针或引用传递给函数时,标准是否保证该对象的生存期将延长到函数生存期?

When we pass an object which is managed by temporary smart pointer to a function by raw pointer or by reference, does the standard guarantee that the object's lifetime will extend to the function lifetime?

#include <iostream>
#include <memory>

struct A {
  ~A() {
    std::cout << "~A()" << std::endl;
  }
};

std::unique_ptr<A> makeA() {
  return std::make_unique<A>();
}

void f(const A& a) {
  std::cout << "f()" << std::endl;
}

int main() {
  f(*makeA());
  return 0;
}

我希望一旦获得原始指针,由 unique_ptr 管理的 A 实例将被销毁,因为它是临时的,并且未绑定到函数参数.所以输出可能是

I would expect that the instance of A managed by unique_ptr is destroyed once the raw pointer is obtained from it, as it is a temporary and it is not bound to function arguments. So the output could be

~A()
f()

但是gcc和clang都可以启用它,直到函数结束,即输出为

But both gcc and clang make it live till the function ends, i.e. the output is

f()
~A()

因此,临时智能指针似乎没有被破坏.

So it seems that the temporary smart pointer is not destroyed.

为什么 A 实例(位于堆中)存活到函数结束?高度赞赏对该标准的一些引用.

Why does the A instance (located in the heap) live till the function end? Some reference to the standard is highly appreciated.

推荐答案

临时文件的生存期一直到创建它们的完整表达式的末尾(某些生命周期延长例外),请参见 [class.temporary]/4 .

Temporaries live until the end of the full-expression in which they were created (with some life time extension exceptions), see [class.temporary]/4.

在您的情况下,类型为 std :: unique_ptr< A> 的感兴趣的临时对象是由 makeA()创建的,而该表达式的全表达式是is的子表达式 f(* makeA()); ,因此临时对象的生存期将以该分号结束.

In your case the temporary of interest of type std::unique_ptr<A> is created by makeA() and the full-expression this is a subexpression of is f(*makeA());, so the temporary's life time will end at that semicolon.

unique_ptr 管理的对象也仅在 unique_ptr 本身被销毁时才销毁(这是智能指针的目的).

The object that the unique_ptr manages is also destroyed only when the unique_ptr itself is destroyed (that is the purpose of the smart pointer).

有关该规则的例外情况,请参阅标准的以下段落.

For exceptions to that rule, see the following paragraph of the standard.

这篇关于函数调用中的C ++临时对象的生存期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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