为什么未命名的 C++ 对象会在作用域块结束之前销毁?

2022-01-04 00:00:00 destructor scope 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
", m_name); }
};

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

推荐答案

一个临时变量一直存在到创建它的完整表达式的结尾.你的变量以分号结尾.

A temporary variable lives until the end of the full expression it was created in. Yours ends at the semicolon.

这是在 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.

相关文章