变量上的 const 与 constexpr

2023-03-09C/C++开发问题
2

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

问题描述

以下定义有区别吗?

const     double PI = 3.141592653589793;
constexpr double PI = 3.141592653589793;

如果不是,那么在 C++11 中更喜欢哪种风格?

If not, which style is preferred in C++11?

推荐答案

我相信是有区别的.让我们重命名它们,以便我们可以更轻松地讨论它们:

I believe there is a difference. Let's rename them so that we can talk about them more easily:

const     double PI1 = 3.141592653589793;
constexpr double PI2 = 3.141592653589793;

PI1PI2 都是常量,意味着你不能修改它们.但是 PI2 是编译时常量.它在编译时初始化.PI1 可以在编译时或运行时初始化.此外, PI2 可以在需要编译时常量的上下文中使用.例如:

Both PI1 and PI2 are constant, meaning you can not modify them. However only PI2 is a compile-time constant. It shall be initialized at compile time. PI1 may be initialized at compile time or run time. Furthermore, only PI2 can be used in a context that requires a compile-time constant. For example:

constexpr double PI3 = PI1;  // error

但是:

constexpr double PI3 = PI2;  // ok

和:

static_assert(PI1 == 3.141592653589793, "");  // error

但是:

static_assert(PI2 == 3.141592653589793, "");  // ok

至于您应该使用哪个?使用满足您需求的任何一种.你想确保你有一个编译时常量可以在需要编译时常量的上下文中使用吗?您是否希望能够使用在运行时完成的计算来初始化它?等

As to which you should use? Use whichever meets your needs. Do you want to ensure that you have a compile time constant that can be used in contexts where a compile-time constant is required? Do you want to be able to initialize it with a computation done at run time? Etc.

这篇关于变量上的 const 与 constexpr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6