const vs constexpr on variables [英] const vs constexpr on variables
问题描述
以下定义之间有区别吗?
Is there a difference between the following definitions?
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;
PI1
和 PI2
是常量,这意味着您无法修改它们。但仅 PI2
是编译时常量。 应在编译时初始化。 PI1
可能在编译时或运行时初始化。此外,在需要编译时常量的上下文中可以使用仅 c $ c $> 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 compiled 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 vs constexpr on variables的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!