Reputation: 3084
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?
Upvotes: 7
Views: 922
Reputation: 4637
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.
Upvotes: 6