【问题标题】:Errors on pointer arithmetics on (char*)(nullptr) evaluating to constexpr(char*)(nullptr) 上的指针算术错误评估为 constexpr
【发布时间】:2023-03-11 01:05:01
【问题描述】:

以下程序在形式上是正确的 C++ 吗?

#include <iostream>
#define CASE 1
#if CASE==1
  constexpr void* crash = static_cast<void*>(static_cast<char*>(nullptr)+1);
#elif CASE==2
  constexpr void* crash = nullptr;
#elif CASE==3
  const void* crash = static_cast<void*>(static_cast<char*>(nullptr)+1);
#endif
int main() {
    std::cout << "Crash: " << crash << "\n";
}

G++ 8.4.0 报告

error: reinterpret_cast from integer to pointer
   constexpr void* crash = static_cast<void*>(static_cast<char*>(nullptr)+1);
                           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Visual Studio 19 cl 报告:

null.cc(3): error C2131: expression did not evaluate to a constant
null.cc(3): note: failure was caused by unevaluable pointer value

如何解释这些错误消息?

如果我将 CASE 的值更改为 2 或 3,则两个编译器的编译都会成功,并且运行已编译的程序会给出预期的结果。

【问题讨论】:

    标签: c++ nullptr


    【解决方案1】:

    您不能只对 constexpr 中的任何指针执行算术运算。
    你可以对指向数组的指针(或作为一种大小的数组的对象)执行算术运算,只要不超出数组即可。

    【讨论】:

    • ...或超出数组末尾的一个元素。
    • 以下两个陈述是否会导致您的答案?如果是这种情况,您可以将它们添加到您的答案中吗? (声明 1)n4713 的第 8.5.6 [expr.add] 节中的第 4 段说static_cast&lt;void*&gt;(static_cast&lt;char*&gt;(nullptr)+1) 给出了未定义的行为。 (语句 2)第 2 段的第 8.6 节 [expr.const] 项 (2.6) 指出,如果指针算术导致未定义的行为,则这不是核心常量表达式。所以constexpr不适用于这个表达式,会导致错误。
    猜你喜欢
    • 2020-09-26
    • 2013-06-03
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多