c++ - 为什么未命名的 C++ 对象会在作用域 block 结束之前破坏?

标签 c++ scope destructor

以下代码打印一、二、三。这对所有 C++ 编译器来说都是期望的和真实的吗?


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 中:

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

你的行为是有保证的。

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

关于c++ - 为什么未命名的 C++ 对象会在作用域 block 结束之前破坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2298781/

相关文章:

c++ - 使析构函数不是虚拟的,并在特殊情况下删除基指针是否安全?

c++ - 在类型化的 std::array 中放置 new 和 std::destroy_at 的安全性?

c++ - 由其他模板类的内部 typedef 定义的类型的模板参数

c++ - 我有静态或动态 boost 库吗?

c++ - 启动时的 Telnet C++ 或 SSH 程序

c++ - 拆分 C++ 模板文件 intp cpp 和 hpp 文件

javascript - 这个脚本发生了什么

javascript - AngularJS:使用 $scope.$watch 和 Controller 作为语法

scope - setq 的 Lisp 作用域问题?

c++ - 析构函数中的动态转换