constexpr const vs constexpr variables? [英] constexpr const vs constexpr variables?

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

问题描述

很明显,constexpr意味着const,因此它是常见的:

It seems obvious that constexpr implies const and thus it is common to see:

constexpr int foo = 42; // no const here

但是如果你写:

constexpr char *const str = "foo";

然后GCC将生成警告:从字符串常量到字符串常量的转换为'char *'if -Wwrite -string标志被传递。

Then GCC will spawn "warning: deprecated conversion from string constant to ‘char*’" if -Wwrite-string flag is passed.

写入:

constexpr const char *const str = "foo";

可解决问题。

constexpr const和constexpr真的一样吗?

So are constexpr const and constexpr really the same?

推荐答案

问题是在变量声明中, constexpr 始终将 const -ness应用于声明的对象; const 另一方面可以应用于不同的类型,取决于位置。

The issue is that in a variable declaration, constexpr always applies the const-ness to the object declared; const on the other hand can apply to a different type, depending on the placement.



Thus

constexpr const int i = 3;
constexpr int i = 3;

等效;

constexpr char* p = nullptr;
constexpr char* const p = nullptr;

两个都使 p a const 指向 char p>

are equivalent; both make p a const pointer to char.

constexpr const char* p = nullptr;
constexpr const char* const p = nullptr;

是等效的。 constexpr 使 p a const 指针。在中的 const 使 p 指向 const char

are equivalent. constexpr makes p a const pointer. The const in const char * makes p point to const char.

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

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