Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

It seems obvious that constexpr implies const and thus it is common to see:

constexpr int foo = 42; // no const here

However if you write:

constexpr char *const str = "foo";

Then GCC will spawn "warning: deprecated conversion from string constant to ‘char*’" if -Wwrite-string flag is passed.

Writing:

constexpr const char *const str = "foo";

solves the issue.

So are constexpr const and constexpr really the same?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
727 views
Welcome To Ask or Share your Answers For Others

1 Answer

The issue is that in a variable declaration, constexpr always applies the const-ness to the object declared; const on the other hand can apply to a different type, depending on the placement.

Thus

constexpr const int i = 3;
constexpr int i = 3;

are equivalent;

constexpr char* p = nullptr;
constexpr char* const p = nullptr;

are equivalent; both make p a const pointer to char.

constexpr const char* p = nullptr;
constexpr const char* const p = nullptr;

are equivalent. constexpr makes p a const pointer. The const in const char * makes p point to const char.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...