Constexpr:与 nullptr 的比较 - 错误或功能?
Constexpr: Comparision to nullptr - Bug or feature?
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");
我的意思是,与 nullptr
的比较应该不同于与其他随机地址的比较。
你会说:这是错误还是解释问题?对我来说,很难为两个编译器编写相同的代码...
GCC 5.0 到 5.4 会发生此错误。在 GCC 6+ 中只有 foobar()
不编译。
这已为 gcc-7 修复。我已经打开:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77539
请求向后移植。
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");
我的意思是,与 nullptr
的比较应该不同于与其他随机地址的比较。
你会说:这是错误还是解释问题?对我来说,很难为两个编译器编写相同的代码...
GCC 5.0 到 5.4 会发生此错误。在 GCC 6+ 中只有 foobar()
不编译。
这已为 gcc-7 修复。我已经打开: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77539 请求向后移植。