为什么未命名的C ++对象在范围块结束之前被销毁? [英] Why do un-named C++ objects destruct before the scope block ends?

查看:233
本文介绍了为什么未命名的C ++对象在范围块结束之前被销毁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码打印一个,两个,三个。对于所有的C ++编译器都是这样吗?

The following code prints one,two,three. Is that desired and true for all C++ compilers?


class Foo
{
      const char* m_name;
public:
      Foo(const char* name) : m_name(name) {}
      ~Foo() { printf("%s\n", m_name); }
};

void main()
{
      Foo foo("three");
      Foo("one");   // un-named object
      printf("two\n");
}


推荐答案

这是在12.2 / 3:

This is in 12.2/3:


临时对象作为评估(词法)包含创建点的完整表达式(1.9)的最后一步被销毁。

Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created.

您的行为得到保证。

有两个条件,如果满足,将延长临时生命周期。第一个是当它是一个对象的初始化时。第二个是当引用绑定到临时。

There are two conditions that, if met, will extend the lifetime of a temporary. The first is when it's an initializer for an object. The second is when a reference binds to a temporary.

这篇关于为什么未命名的C ++对象在范围块结束之前被销毁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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