問(wèn)題描述
以下定義有區(qū)別嗎?
const double PI = 3.141592653589793;
constexpr double PI = 3.141592653589793;
如果不是,那么在 C++11 中更喜歡哪種風(fēng)格?
If not, which style is preferred in C++11?
推薦答案
我相信是有區(qū)別的.讓我們重命名它們,以便我們可以更輕松地討論它們:
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
是編譯時(shí)常量.它應(yīng)在編譯時(shí)初始化.PI1
可以在編譯時(shí)或運(yùn)行時(shí)初始化.此外,僅 PI2
可以在需要編譯時(shí)常量的上下文中使用.例如:
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
至于您應(yīng)該使用哪個(gè)?使用滿足您需求的任何一種.你想確保你有一個(gè)編譯時(shí)常量可以在需要編譯時(shí)常量的上下文中使用嗎?您是否希望能夠使用在運(yùn)行時(shí)完成的計(jì)算來(lái)初始化它?等
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.
這篇關(guān)于變量上的 const 與 constexpr的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!