Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should one set the constructor as constexpr?

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?

like image 451
G.Rassovsky Avatar asked Nov 14 '14 14:11

G.Rassovsky


People also ask

Should constructors be constexpr?

every constructor selected to initializing non-static data members and base class must be a constexpr constructor.

Why should I use constexpr?

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.

What does constexpr constructor mean?

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.

Is constexpr a default constructor?

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.


1 Answers

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.

like image 199
Mike Seymour Avatar answered Sep 19 '22 16:09

Mike Seymour