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

问题描述

cppreference 指出:


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


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是否冗余?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:44