constexpr

When should you use constexpr capability in C++11?

扶醉桌前 提交于 2019-11-25 23:16:11
It seems to me that having a "function that always returns 5" is breaking or diluting the meaning of "calling a function". There must be a reason, or a need for this capability or it wouldn't be in C++11. Why is it there? // preprocessor. #define MEANING_OF_LIFE 42 // constants: const int MeaningOfLife = 42; // constexpr-function: constexpr int MeaningOfLife () { return 42; } It seems to me that if I wrote a function that return a literal value, and I came up to a code-review, someone would tell me, I should then, declare a constant value instead of writing return 5. Suppose it does something

Difference between `constexpr` and `const`

末鹿安然 提交于 2019-11-25 22:46:55
问题 What\'s the difference between constexpr and const ? When can I use only one of them? When can I use both and how should I choose one? 回答1: Basic meaning and syntax Both keywords can be used in the declaration of objects as well as functions. The basic difference when applied to objects is this: const declares an object as constant . This implies a guarantee that, once initialized, the value of that object won't change, and the compiler can make use of this fact for optimizations. It also

Why do constant expressions have an exclusion for undefined behavior?

て烟熏妆下的殇ゞ 提交于 2019-11-25 19:36:52
I was researching what is allowed in a core constant expression* , which is covered in section 5.19 Constant expressions paragraph 2 of the draft C++ standard which says: A conditional-expression is a core constant expression unless it involves one of the following as a potentially evaluated subexpression (3.2), but subexpressions of logical AND (5.14), logical OR (5.15), and conditional (5.16) operations that are not evaluated are not considered [ Note: An overloaded operator invokes a function.—end note ]: and lists out the exclusions in the bullets that follows and includes ( emphasis mine