以下代码打印一、二、三。这对所有 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/