Does constexpr in pointers value

What is the difference between constexpr int *np = nullptr and int const *np = nullptr ?

np is a constant pointer to int, which is null in both cases. Is there any specific use for constexpr in the context of pointers.

+7
c ++ pointers c ++ 11 constant-expression
source share
1 answer

If you try to do something with the pointer and use the result in a constant expression, then the pointer should be marked as constexpr. A simple example is pointer arithmetic or pointer dereferencing:

 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; 

In the above example, second may be constexpr if first . Similarly *second can only be a constant expression if second is constexpr

If you try to call the constexpr member constexpr via a pointer and use the result as a constant expression, the pointer you call it must itself be a constant expression

 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 } 

If we say

 constexpr const S *sp = &s; 

then the above work. Please note that the above (incorrectly) compiled and executed with gcc-4.9 but not gcc-5.1

+3
source share

All Articles