c++ constexpr const char * vs constexpr const char []

栏目: C++ · 发布时间: 6年前

内容简介:代码日志版权声明:翻译自:http://stackoverflow.com/questions/33692872/constexpr-const-char-vs-constexpr-const-char

第一次尝试不会编译,而第二次尝试.为什么?有什么不同?

第一次尝试:

#include <iostream>

int main()
{
    constexpr const char text2[] = "hello";
    constexpr const char * b = &text2[4];  // error: '& text2[4]' is not a constant expression
    std::cout << b << std::endl;
}

第二次尝试:

#include <iostream>
int main()
{
constexpr const char * text1 = "hello";
constexpr const char * a = &text1[4];
std::cout << a << std::endl;

return 0;
}

我编译(g版本4.9.2)

g++ -std=c++11 -o main *.cpp

这给出了以下错误

main.cpp: In function 'int main()':
main.cpp:7:40: error: '& text2[4]' is not a constant expression constexpr const char * b = &text2[4];  // error: '& text2[4]' is not a constant expression
从C11标准5.19 [expr.const]草案可以看出, address constant expression

是(重点是煤锣前进):

[…] a prvalue core constant expression

of

pointer type that evaluates to the address of an object with

, to the address of a function, or to a null

pointer value, or a prvalue core constant expression of type

std::nullptr_t.

在第一种情况下,虽然“hello”是一个具有静态存储持续时间的字符串文字.它被复制到没有静态存储持续时间的数组text2中.

而在第二种情况下,text1是指向具有静态存储持续时间的 string literal 的指针.

改变你的第一个例子,使text2 static( see it live ):

constexpr char static text2[] = "hello";
               ^^^^^^

我们不再收到错误.

我们可以看到一个字符串文字具有从2.14.5节[lex.string]的静态存储时间:

Ordinary string literals and UTF-8 string literals are also referred  to as narrow string literals. A narrow string literal has type “array  of n const char”, where n is the size of the string as defined below,  and has static storage duration (3.7).

代码日志版权声明:

翻译自:http://stackoverflow.com/questions/33692872/constexpr-const-char-vs-constexpr-const-char


以上所述就是小编给大家介绍的《c++ constexpr const char * vs constexpr const char []》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

高可用架构(第1卷)

高可用架构(第1卷)

高可用架构社区 / 电子工业出版社 / 2017-11-1 / 108.00元

《高可用架构(第1卷)》由数十位一线架构师的实践与经验凝结而成,选材兼顾技术性、前瞻性与专业深度。各技术焦点,均由极具代表性的领域专家或实践先行者撰文深度剖析,共同组成“高可用”的全局视野与领先高度,内容包括精华案例、分布式原理、电商架构等热门专题,及云计算、容器、运维、大数据、安全等重点方向。不仅架构师可以从中受益,其他IT、互联网技术从业者同样可以得到提升。一起来看看 《高可用架构(第1卷)》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具