Shubham Chaudhary
Shubham Chaudhary

Reputation: 93

Does constexpr in pointers make a difference

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

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

Upvotes: 7

Views: 993

Answers (1)

Ryan Haining
Ryan Haining

Reputation: 36882

If you try to do anything with the pointer and use the result in a constant expression, then the pointer must be marked as constexpr. The 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 can only be constexpr if first is. Similarly *second can only be a constant expression if second is constexpr

If you try to call a constexpr member function through a pointer and use the result as a constant expression, the pointer you call it through 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 instead say

constexpr const S *sp = &s;

then the above works works. Please note that the above does (incorrectly) compiled and run with gcc-4.9, but not gcc-5.1

Upvotes: 3

Related Questions