为什么要为字符串文字声明将const添加到constexpr?

问题描述 投票:3回答:1

此声明:

char constexpr *const s = "hello";

此错误失败:

g++ -g -Wall -Werror -std=c++17 test.cc -o test
test.cc:8:31: error: ISO C++11 does not allow conversion from string literal to 'char *const' [-Werror,-Wwritable-strings]
char constexpr *const s = "hello";

但是如果我将const添加到constexpr,则编译器很高兴:

char const constexpr *const s = "hello";

编译:

g++ -g -Wall -Werror -std=c++17 test.cc -o test
./test
hello

对我来说这似乎不直观。为什么const需要装饰constexpr? constexpr不暗示const吗?如果它是一个编译器常量,那么在其他意义上又不是常量吗?是否有可能将其作为constexpr但以其他方式更改(例如,不是恒定的)?

这里是一个最小的螺栓:

https://godbolt.org/z/sSQMVa

c++ const constexpr
1个回答
1
投票

不是constexpr隐含const吗?


0
投票

[const适用于其左侧的东西,或者如果什么也没有,那么其右侧。

© www.soinside.com 2019 - 2024. All rights reserved.