Different behavior is observed with the variable constexpr auto / char -array

Following this question Having a static string constexpr gives a linker error

In this question this code could not compile:

#include <iostream> struct Test { static constexpr char text[] = "Text"; }; int main() { std::cout << Test::text << std::endl; // error: undefined reference to `Test::text' } 

From the comment, this code can compile:

 #include <iostream> struct Test { static constexpr auto text = "Text"; }; int main() { std::cout << Test::text << std::endl; } 

My question is: why does the auto version work, but the char version array does not work?

Could you point out the statement in the standard that allows the second version and prohibits the first?

I looked at the weird behavior with the constexpr constant variable , but it seems to be another question.

+4
source share
2 answers

Declaring a static data member in a class is never a definition. The difference between your examples is that only one requires a definition of text .

The auto version outputs char const* , so text only applies to the lvalue-to-rval conversion, not odr. On the contrary, the first code efficiently passes the text address using it, i.e. Requires definition.

+8
source
 struct Test { static constexpr auto text = "Text"; }; 

permits

 struct Test { static constexpr const char * text = "Text"; }; 

So, the second expression is a constexpr value of the pointer, not an array.

+2
source

Source: https://habr.com/ru/post/1240623/


All Articles