Why do un-named C++ objects destruct before the scope block ends?(为什么未命名的 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.
这篇关于为什么未命名的 C++ 对象会在作用域块结束之前销毁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么未命名的 C++ 对象会在作用域块结束之前销毁?
基础教程推荐
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- c++ STL设置差异 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
