Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11: constexpr constructor performance

Tags:

c++11

I got little confused with constepxt ctors..

Does the following is as just as fast (or faster)

while(true)
{
   constexpr std::chrono::hours one_hour(1);
   ..
}

than (creating only one instance):

while(true)
{
   static constexpr std::chrono::hours one_hour(1);
   ..
}

In other words, Does constexpr ctor means no runtime overhead whatsoever?

like image 586
GabiMe Avatar asked Dec 01 '25 20:12

GabiMe


1 Answers

Does constexpr ctor means no runtime overhead whatsoever?

When in doubt, you can always check; for example:

#include <chrono>

template <long Long>
class dummy { };

int main() {

  constexpr std::chrono::hours one_hour(1);

  dummy<one_hour.count()> d; 
}

The fact that it compiles means that one_hour is a compile time constant and as such, has no runtime overhead whatsoever.

like image 99
Ali Avatar answered Dec 03 '25 16:12

Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!