【问题标题】:Constexpr: Comparision to nullptr - Bug or feature?Constexpr:与 nullptr 的比较 - 错误或功能?
【发布时间】:2016-09-09 06:35:29
【问题描述】:

GCC 无法将某些表达式评估为常量。然而,Clang 很好用。

/*
 */
constexpr int foo(const int * array)
{
  if (array == nullptr) // Error: '(((const int*)(& array)) == 0u)' is not a constant expression
  {
    return 0;
  }

  return 1;
}

constexpr int bar()
{
  int array[100] = {};

  return foo(array);
}

static_assert(bar() == 1, "outch..."); // Does not compile. See above.
static_assert(foo(nullptr) == 0, "okay");

constexpr int i[100] = {};
static_assert(foo(i) == 1, "okay");

也不行:

constexpr int foobar()
{
  int array[100] = {};
  int *ar = array;
  if (ar == nullptr) // Error...
  {
    return 0;
  }
  return 1;
}

static_assert(foobar() == 1, "okay");

同样的事情:

constexpr int foo2()
{ 
  int *a = nullptr;
  if (a == nullptr) // Error...
  {
    return 0;
  } 
  return 1;
}

static_assert(foo2() == 0, "okay");

Live Example

我的意思是,与nullptr 的比较应该不同于与其他随机地址的比较。

你会说:这是一个错误还是解释问题?对我来说,很难为两个编译器编写相同的代码...

GCC 5.0 到 5.4 会发生此错误。在 GCC 6+ 中,只有 foobar() 无法编译。

【问题讨论】:

    标签: c++ gcc c++14 constexpr


    【解决方案1】:

    这已经为 gcc-7 修复了。我已经打开了: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77539 请求反向移植。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-27
      • 1970-01-01
      • 1970-01-01
      • 2014-10-28
      • 2019-09-03
      • 2016-03-30
      • 2023-03-11
      • 2021-04-09
      相关资源
      最近更新 更多