c++ - 什么是具有静态存储期限的临时对象

标签 c++ language-lawyer

灵感来自 this answer , 来自 [expr.const]

A constant expression is either a glvalue core constant expression that refers to an entity that is a permitted result of a constant expression (as defined below), or a prvalue core constant expression whose value satisfies the following constraints:

  • if the value is an object of class type, each non-static data member of reference type refers to an entity that is a permitted result of a constant expression,

  • if the value is of pointer type, it contains the address of an object with static storage duration, the address past the end of such an object ([expr.add]), the address of a function, or a null pointer value, and

  • if the value is an object of class or array type, each subobject satisfies these constraints for the value.

An entity is a permitted result of a constant expression if it is an object with static storage duration that is either not a temporary object or is a temporary object whose value satisfies the above constraints, or it is a function.

究竟什么是具有静态存储持续时间的临时对象?我是否遗漏了某些东西,或者一个对象既是临时的又具有静态存储持续时间是自相矛盾的吗?

来自 [basic.stc.static] 的定义

All variables which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration. The storage for these entities shall last for the duration of the program

仅适用于变量

最佳答案

[basic.stc]/1 告诉我们:

The storage duration is the property of an object that defines the minimum potential lifetime of the storage containing the object.

所以每个对象都有一个存储期限。此外,第 2 段说:

Static, thread, and automatic storage durations are associated with objects introduced by declarations (6.1) and implicitly created by the implementation (15.2).

添加了重点。请注意,第 15.2 节是 [class.temporary]:临时对象的规则。

因此,我们可以得出结论,临时对象具有存储持续时间。我们可以得出结论,临时对象必须具有这些存储持续时间之一。事实上,标准中有许多关于“变量或临时对象”及其存储期限的引用。

但是,尽管这清楚地表明临时对象具有其中一种存储期限……但标准从未真正说明它们具有的存储期限。 [class.temporary] 没有声明说绑定(bind)到引用的临时对象具有其引用的存储持续时间。而且 [basic.stc] 对静态、自动和线程本地持续时间的解释总是提到变量。

所以我会说这是措辞上的缺陷。标准期望临时对象有适当的存储持续时间似乎很清楚;该标准在多个地方讨论了变量或临时对象的存储持续时间。但它从未说明它们实际拥有的存储期限。

关于c++ - 什么是具有静态存储期限的临时对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47945299/

相关文章:

c++ - 使用来自元函数的 typedef 声明成员函数

c++ - 什么是 gcc Wmaybe-未初始化警告

c++ - 使用 arm-none-eabi 进行 Clang 交叉编译

c++ - 对 `saving::rate' 的 undefined reference

c++ - typedef 和非简单类型说明符

c++ - 使用派生自 `std::get` 的元素在 `std::tuple` 上调用 `std::tuple` - 格式错误?

c++ - 如果不使用模板类中的定义,是否应该实例化?

c++ - rand() 总是在应用程序重启时返回相同的序列

c++ - 多个文件中的类实现

c++ - 不同翻译单元中不可重载的非内联函数定义