gpt4 book ai didi

c++ - Constexpr:与 nullptr 的比较 - 错误或功能?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:36:54 24 4
gpt4 key购买 nike

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() 无法编译。

最佳答案

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

关于c++ - Constexpr:与 nullptr 的比较 - 错误或功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39405241/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com