用 const char*const 解释 constexpr
Explain constexpr with const char*const
我有以下代码:
static constexpr const char*const myString = "myString";
能否请您解释一下与以下内容的区别:
static const char*const myString = "myString";
在这种情况下,constexpr 有什么新功能?
C++ 标准(9.4.2 静态数据成员)中的以下引用描述了差异
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.
例如考虑两个程序
struct A
{
const static double x = 1.0;
};
int main()
{
return 0;
}
struct A
{
constexpr static double x = 1.0;
};
int main()
{
return 0;
}
第一个不会编译,而第二个会编译。
同样适用于指针
这个节目
struct A
{
static constexpr const char * myString = "myString";
};
int main()
{
return 0;
}
将编译此程序
struct A
{
static const char * const myString = "myString";
};
int main()
{
return 0;
}
不会编译。
我有以下代码:
static constexpr const char*const myString = "myString";
能否请您解释一下与以下内容的区别:
static const char*const myString = "myString";
在这种情况下,constexpr 有什么新功能?
C++ 标准(9.4.2 静态数据成员)中的以下引用描述了差异
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.
例如考虑两个程序
struct A
{
const static double x = 1.0;
};
int main()
{
return 0;
}
struct A
{
constexpr static double x = 1.0;
};
int main()
{
return 0;
}
第一个不会编译,而第二个会编译。
同样适用于指针
这个节目
struct A
{
static constexpr const char * myString = "myString";
};
int main()
{
return 0;
}
将编译此程序
struct A
{
static const char * const myString = "myString";
};
int main()
{
return 0;
}
不会编译。