I am aware that c++11 allows for specifying expressions for compile-time rather than run-time by using constexpr.
I know that this could be done for the constructor of a class too. However, this constructor has to initialize all the members of the class, in order to be used as a constexpr (in compile-time), and any functions that it calls should also be marked as constexpr.
But when would one set his constructor to a constexpr, and are there any other benefits apart from slight optimisation?
Would that mean that, if I CAN, I should ALWAYS set my constructor as constexpr?
every constructor selected to initializing non-static data members and base class must be a constexpr constructor.
A constexpr integral value can be used wherever a const integer is required, such as in template arguments and array declarations. And when a value is computed at compile time instead of run time, it helps your program run faster and use less memory.
Constant Expression Constructors A constexpr constructor allows the compiler to initialize the object at compile-time, provided that the constructor's arguments are all constant expressions. Formally, a constant expression constructor is one that meets the following criteria: It's declared constexpr explicitly.
If that user-defined default constructor would satisfy the requirements of a constexpr constructor, the implicitly defined default constructor is a constexpr constructor. A constexpr constructor is implicitly inline.
By making the constructor constexpr
, you allow users to create constexpr
objects, and use them in their own constant expressions. This makes the class friendlier in some circumstances; for example, when programming for an embedded system where you want to put data in read-only memory if possible.
So, from the point of view of making the class as flexible and generally useful as possible, you should do so if you can.
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