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

2023-10-17C/C++开发问题
3

本文介绍了为什么未命名的 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++ 对象会在作用域块结束之前销毁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6