【问题标题】:Can one volatile constexpr variable initialize another one in C++?一个 volatile constexpr 变量可以在 C++ 中初始化另一个吗?
【发布时间】:2022-11-21 06:49:26
【问题描述】:

C++ 标准允许每个 defect report 1688constexpr volatile 变量,该问题已于 2013 年 9 月解决:

这种组合是有意允许的,并且可以在某些情况下用于强制常量初始化。

看起来其意图是仅允许 constinit volatile,这在 C++20 之前是不可用的。

在某些情况下,当前的编译器在处理 constexpr volatile 时仍然存在分歧。例如,这个程序用另一个变量初始化一个这样的变量:

int main() {
    constexpr volatile int i = 0;
    constexpr volatile int j = i;
    return j;
}

它在 GCC 和 MSVC 中被接受,但 Clang 抱怨:

error: constexpr variable 'j' must be initialized by a constant expression
    constexpr volatile int j = i;
                           ^   ~
note: read of volatile-qualified type 'const volatile int' is not allowed in a constant expression
    constexpr volatile int j = i;

在线演示:https://gcc.godbolt.org/z/43ee65Peq

哪个编译器就在这里,为什么?

【问题讨论】:

    标签: c++ language-lawyer constexpr volatile


    【解决方案1】:

    您链接的缺陷报告显示它不应该工作,所以 Clang 是正确的。

    (...) “用 constexpr 定义的非易失性对象” (...) 是允许的,但这样的变量不能出现在常量表达式中.意图是什么?

    但更有趣的是:为什么 Clang 关心而其他编译器不关心?

    在我看来,这是因为 JF Bastien 是 Clang / LLVM 世界中非常有影响力的人物,他个人不喜欢 volatile :)

    他是proposing to remove它从一门语言很久了。因此,如果允许在某个地方禁止使用 volatile,他可能会不遗余力地做到这一点。如果没有其他原因,那么只是为了防止人们编写如果他的建议最终被接受就必须重写的代码。

    如果您想知道他的推理,他还在 CppCon 上做了关于他的 depreciation proposal 的演示。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-12
      • 1970-01-01
      • 2014-04-13
      • 1970-01-01
      相关资源
      最近更新 更多