G.Rassovsky
G.Rassovsky

Reputation: 804

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?

Upvotes: 18

Views: 1073

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254461

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.

Upvotes: 16

Related Questions