Should I always replace 'const int' with 'constexpr int' in C++11 whenever possible?

随声附和 提交于 2019-12-08 16:33:35

问题


Would you replace

const int one = 1;
const int two = 2;

with this?

constexpr int one = 1;
constexpr int two = 2;

Is my understanding correct that both blocks are semantically identical and that it is currently merely a matter of taste?

On the other hand, as constexpr implies const, you could argue that it is more consistent to always prefer the more restrictive form, even in trivial situations where it does not make a difference?

(I understand that the situation completely changes when the expression on the right side are allowed to be more complicated. So for clarification, the question only focuses on the most simple case where the expression is a fixed integer number.)


回答1:


I think your statement saying that const and constexpr "are semantically identical" should be revised: they both declare objects whose value cannot change, but constexpr also requires the initializer expression to be computable at compile-time.

Now if the expression on the right-hand side cannot be computed at compile-time, using constexpr is out of the question. On the other hand, as long as the initializer is a literal, you could use constexpr, but keep into account what the semantics of your variable is: does your constant variable really represent something whose value should be computable at compile-time?

In a SW maintenance/evolution optics, it is possible that you will change the way you initialize your variable throughout time: today the initializer is a literal, tomorrow it might be a more complex expression.

Regardless of the way you are assigning it a value now, do you think that i will ever need to be initialized by anything else than a literal, and that the initializing expression may not be computable at compile-time? If that is the case, then just make your variable const, even though you are currently initializing it with a literal; otherwise, make it constexpr.

In other words, choose the qualifier that best expresses the semantics of your variable.



来源:https://stackoverflow.com/questions/15078689/should-i-always-replace-const-int-with-constexpr-int-in-c11-whenever-possi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!