可以在 constexpr 上下文中使用导致未指定(不是未定义!)行为的指针的表达式吗?
Can expression using pointers causing unspecified (not undefined!) behaviour be used in constexpr context?
根据cppreference(强调我的):
A core constant expression is any expression that does not have any
one of the following in any subexpression
(...)
- An expression whose evaluation leads to any form of core language
undefined behavior (including signed integer overflow, division by
zero, pointer arithmetic outside array bounds, etc). Whether standard
library undefined behavior is detected is unspecified.
另一方面,有几个指针表达式的结果不是未定义的,而是 未指定的(参见 [expr.rel]/3)例如:
struct A {
int v;
};
struct B {
int v;
};
struct C: A, B {} c;
int main() {
constexpr bool result = &c.A::v < &c.B::v;
(void)result;
}
代码在 gcc but not in clang 下编译没有问题,这无疑表明:
comparison of addresses of subobjects of different base classes has unspecified
但是(据我所知)根据 cppreference 它不应该阻止编译器编译代码。
这里是哪个编译器 - gcc 还是 clang?我是否过度解读了 cppreference?
除了关于 UB 的包罗万象的情况之外,[expr.const] 中禁止表达列表的末尾是,
— a relational or equality operator where the result is unspecified
这也出现在 cppreference 列表中,当前编号为 #19。
根据cppreference(强调我的):
A core constant expression is any expression that does not have any one of the following in any subexpression
(...)
- An expression whose evaluation leads to any form of core language undefined behavior (including signed integer overflow, division by zero, pointer arithmetic outside array bounds, etc). Whether standard library undefined behavior is detected is unspecified.
另一方面,有几个指针表达式的结果不是未定义的,而是 未指定的(参见 [expr.rel]/3)例如:
struct A {
int v;
};
struct B {
int v;
};
struct C: A, B {} c;
int main() {
constexpr bool result = &c.A::v < &c.B::v;
(void)result;
}
代码在 gcc but not in clang 下编译没有问题,这无疑表明:
comparison of addresses of subobjects of different base classes has unspecified
但是(据我所知)根据 cppreference 它不应该阻止编译器编译代码。
这里是哪个编译器 - gcc 还是 clang?我是否过度解读了 cppreference?
除了关于 UB 的包罗万象的情况之外,[expr.const] 中禁止表达列表的末尾是,
— a relational or equality operator where the result is unspecified
这也出现在 cppreference 列表中,当前编号为 #19。