const constexpr char *与constexpr char * [英] const constexpr char* vs. constexpr char*

查看:746
本文介绍了const constexpr char *与constexpr char *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道const和constexpr之间的区别。一个是编译时间常数,另一个是编译时间常数或运行时常数。

I know the difference between const and constexpr. One is a compile time constant and the other is either compile time or runtime constant.

但是,对于字符/字符串数组,我很困惑为什么编译器会抱怨

However, for array of chars/strings, I'm confused why the compiler complains about one being used over the other.

例如我有:

constexpr char* A[2] = {"....", "....."};

const constexpr char* B[2] = {"....", "....."};

使用声明 A,我得到:

With declaration "A" I get:

ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

但声明为 B时,我没有警告。

but with declaration "B" I get no warnings.

为什么多余的const修饰符会消除警告?他们都不都是 const char *吗?我问,因为两者都是用 constexpr 声明的,默认情况下应该使它成为 const char * 吗?

Why does the extra const qualifier get rid of the warning? Aren't both of them "const char*" anyway? I ask because both are declared with constexpr which should make it a const char* by default?

我希望A可以:S

推荐答案

const 告诉编译器不应将您指向的字符写入。

const tells the compiler that the chars you are pointing to should not be written to.

constexpr 告诉编译器,可以在编译时完全评估存储在这些数组中的指针。但是,它并没有说指针所指向的字符是否可能会改变。

constexpr tells the compiler that the pointers you are storing in those arrays can be totally evaluated at compile time. However, it doesn't say whether the chars that the pointers are pointing to might change.

顺便说一句,您可以编写此代码的另一种方式是:

By the way, another way you could write this code would be:

const char * const B[2];

第一个 const 适用于字符,第二个 const 应用于数组本身及其包含的指针。

The first const applies to the chars, and the second const applied to the array itself and the pointers it contains.

这篇关于const constexpr char *与constexpr char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆