I have the following code:
static constexpr const char*const myString = "myString";
Could you please explain what is the difference from:
static const char*const myString = "myString";
What's new we have with constexpr in this case?
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.
constexpr specifies that the value of an object or a function can be evaluated at compile-time and the expression can be used in other constant expressions. Example: CPP.
A constructor that is declared with a constexpr specifier is a constexpr constructor. Previously, only expressions of built-in types could be valid constant expressions. With constexpr constructors, objects of user-defined types can be included in valid constant expressions.
Simple: "char *name" name is a pointer to char, i.e. both can be change here. "const char *name" name is a pointer to const char i.e. pointer can change but not char.
The difference is described in the following quote from the C++ Standard (9.4.2 Static data members)
3 If a non-volatile const static data member is of integral or enumeration type, its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignmentexpression is a constant expression (5.19). A static data member of literal type can be declared in the class definition with the constexpr specifier; if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. [ Note: In both these cases, the member may appear in constant expressions. —end note ] The member shall still be defined in a namespace scope if it is odr-used (3.2) in the program and the namespace scope definition shall not contain an initializer.
Consider for example two programs
struct A
{
const static double x = 1.0;
};
int main()
{
return 0;
}
struct A
{
constexpr static double x = 1.0;
};
int main()
{
return 0;
}
The first one will not compile while the second one will compile.
The same is valid for pointers
This program
struct A
{
static constexpr const char * myString = "myString";
};
int main()
{
return 0;
}
will compile while this porgram
struct A
{
static const char * const myString = "myString";
};
int main()
{
return 0;
}
will not compile.
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