变量上的const constexpr是否冗余? [英] Is `const constexpr` on variables redundant?

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

问题描述

cppreference 指出:

在对象声明或非静态中使用的constexpr说明符成员函数(直到C ++ 14)隐含const.

A constexpr specifier used in an object declaration or non-static member function (until C++14) implies const.


对象声明"是指任何变量声明"吗?


Does "object declaration" mean "any variable declaration"?

即是

constexpr const int someConstant = 3;

等同于

constexpr int someConstant = 3;

在C ++ 11,C ++ 14和C ++ 17中?

in C++11, C++14 and C++17?

推荐答案

在带有基元的声明中(例如您的示例中的声明), const 确实是多余的.但是,在某些情况下可能需要 const ,例如

In declarations with primitives, such as the one in your example, const is indeed redundant. However, there may be odd situations where const would be required, for example

constexpr int someConstant = 3;
constexpr const int *someConstantPointerToConstant = &someConstant;

在这里, someConstantPointerToConstant 既是 constexpr (即在编译时就已知,因此也是 constexpr ),并且它也是指向常量的指针(即其对象无法更改,因此 const ).上面的第二个声明不能使用省略的 const 进行编译(演示).

Here, someConstantPointerToConstant is both a constexpr (i.e. it's known at compile time, hence constexpr) and it is also a pointer to constant (i.e. its object cannot be changed, hence const). The second declaration above would not compile with const omitted (demo).

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

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