Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 645
Shubham Chaudhary Avatar asked Aug 18 '15 06:08

Shubham Chaudhary


People also ask

What is the point of constexpr?

constexpr indicates that the value, or return value, is constant and, where possible, is computed at compile time. A constexpr integral value can be used wherever a const integer is required, such as in template arguments and array declarations.

What does constexpr const mean?

constexpr creates a compile-time constant; const simply means that value cannot be changed.


1 Answers

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

like image 125
Ryan Haining Avatar answered Sep 19 '22 23:09

Ryan Haining