I am really confused about a constexpr
concept, as I have read constexpr
is evaluated at compile time, so it is useful for performance optimization versus normal const
.
constexpr int i = 0;
constexpr int& ri = i;
The above code returns an error "invalid initialization of reference of type 'int&' from expression of type 'const int'", why?
Also, the next code has an error:
constexpr int i = 0;
constexpr int* ri = &i;
If I replaced the constexpr
keyword with const
, all above worked correctly.
#define directives create macro substitution, while constexpr variables are special type of variables. They literally have nothing in common beside the fact that before constexpr (or even const ) variables were available, macros were sometimes used when currently constexpr variable can be used.
static defines the object's lifetime during execution; constexpr specifies that the object should be available during compilation. Compilation and execution are disjoint and discontiguous, both in time and space. So once the program is compiled, constexpr is no longer relevant.
A constructor that is declared with a constexpr specifier is a constexpr constructor. Previously, only expressions of built-in types could be valid constant expressions. With constexpr constructors, objects of user-defined types can be included in valid constant expressions.
Using constexpr to Improve Security, Performance and Encapsulation in C++ constexpr is a new C++11 keyword that rids you of the need to create macros and hardcoded literals. It also guarantees, under certain conditions, that objects undergo static initialization.
constexpr int i = 0;
constexpr int * ri = &i;
The second line is a problem because the pointer does not point to a const
object. The pointer itself is const
.
Using
constexpr int i = 0;
constexpr int const * ri = &i;
solves that problem. However, that will be still a problem if the variables are defined in a function scope.
constexpr int i = 0;
constexpr int const* ri = &i;
int main() {}
is a valid program.
void foo()
{
constexpr int i = 0;
constexpr int const* ri = &i;
}
int main() {}
is not a valid program.
Here's what the C++11 standard has to say about address constant expression:
5.19 Constant expressions
3 .. An address constant expression is a prvalue core constant expression of pointer type that evaluates to the address of an object with static storage duration, to the address of a function, or to a null pointer value, or a prvalue core constant expression of type
std::nullptr_t
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With