constexpr int *np = nullptr
和int const *np = nullptr
之间的区别是什么?
np
是一个指向int的常量指针,在两种情况下都是null。在指针的上下文中是否有constexpr
的特定用法。
答案 0 :(得分:3)
如果您尝试对指针执行任何操作并在常量表达式中使用结果,则必须将指针标记为constexpr。简单的例子是指针算术或指针解除引用:
address[0]['street'] #will give you street in first dict
address[1]['street'] #will give you street in second dict
在上面的示例中,如果static constexpr int arr[] = {1,2,3,4,5,6};
constexpr const int *first = arr;
constexpr const int *second = first + 1; // would fail if first wasn't constexpr
constexpr int i = *second;
,则second
只能是constexpr
。同样,如果first
为*second
second
只能是常量表达式
如果尝试通过指针调用constexpr
成员函数并将结果用作常量表达式,则调用它的指针本身必须是常量表达式
constexpr
如果我们改为说
struct S {
constexpr int f() const { return 1; }
};
int main() {
static constexpr S s{};
const S *sp = &s;
constexpr int i = sp->f(); // error: sp not a constant expression
}
然后上述工作有效。请注意,上述(不正确)编译并使用gcc-4.9运行,但不是gcc-5.1