C++ 用 const char*const 解释 constexpr

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29844028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 21:14:24  来源:igfitidea点击:

Explain constexpr with const char*const

c++c++11constconstexpr

提问by demonplus

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 有什么新功能?

采纳答案by Vlad from Moscow

The difference is described in the following quote from the C++ Standard (9.4.2 Static data members)

以下引用来自 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-initializerin 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-initializerin 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.

3 如果一个非 volatile const 静态数据成员是整型或枚举类型,它在类定义中的声明可以指定一个大括号或等号初始值设定项,其中每个作为赋值表达式的初始值设定项子句都是一个常量表达式 (5.19) . 可以在类定义中使用 constexpr 说明符声明文字类型的静态数据成员;如果是这样,它的声明应指定一个大括号或相等的初始化程序其中每个作为赋值表达式的初始化子句都是一个常量表达式。[ 注意:在这两种情况下,成员都可能出现在常量表达式中。—尾注] 如果该成员在程序中被 odr-used (3.2) 使用,则该成员仍应在命名空间范围内定义,并且命名空间范围定义不应包含初始化程序。

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

将在此 porgram 时编译

struct A
{
    static const char * const myString = "myString";
};

int main() 
{
    return 0;
}

will not compile.

不会编译。