I'm totally frustrated with these specifiers because I understand what they do when they're by themselves but I find them hard to understand when they're used with each other. For example, some code in the wild contained -
namespace{
static constexpr char const *Hello[] = { "HelloString", "WorldString"};
...
}
what does this even do?
const
would do?const *Hello
doesn't makes sense to me. What is constant here? The strings or the pointer *Hello
?And worst of all, it compiles :/. Ofcourse it would compile because they're valid statements, but what does it even means?
The keyword constexpr was introduced in C++11 and improved in C++14. It means constant expression. Like const , it can be applied to variables: A compiler error is raised when any code attempts to modify the value.
static defines the object's lifetime during execution; constexpr specifies that the object should be available during compilation. Compilation and execution are disjoint and discontiguous, both in time and space. So once the program is compiled, constexpr is no longer relevant.
The principal difference between const and constexpr is the time when their initialization values are known (evaluated). While the values of const variables can be evaluated at both compile time and runtime, constexpr are always evaluated at compile time.
A static constexpr variable has to be set at compilation, because its lifetime is the the whole program. Without the static keyword, the compiler isn't bound to set the value at compilation, and could decide to set it later.
Why use static when you're already inside an anonymous namespace?
I don't see a reason to here, unless it is written for C++03 compatibility.
Why use
constexpr
- there's no reason to use it here. wouldn't a simple const would do?
Again, it isn't necessary here, but it does indicate that it is a compile time constant. Also note that constexpr
here means the pointer is constexpr
, and removes the need for const
after the *
(see next part).
const *Hello
doesn't makes sense to me. What is constant here? The strings or the pointer *Hello?
const
applies to the left, unless there is nothing there in which case it applies to the right. const
to the left of *
means the pointer when dereferenced is a constant, while to the right means it is a constant pointer to something.
char const * ptr = "Foo";
ptr[0] = 'B'; //error, ptr[0] is const
char * const ptr = "Foo";
ptr = new char[10]; //error, ptr is const
char const * const ptr = "Foo"; //cannot assign to either ptr or *ptr
constexpr char const* ptr = "Foo"; //same as above, constexpr replaced last const
I found that this page on the "right left" rule really helps with understanding complicated declarations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With