C++ 11:constexpr构造函数性能

Gab*_*iMe 3 c++11

我对constepxt ctors感到困惑.

以下是否同样快(或更快)

while(true)
{
   constexpr std::chrono::hours one_hour(1);
   ..
}
Run Code Online (Sandbox Code Playgroud)

比(仅创建一个实例):

while(true)
{
   static constexpr std::chrono::hours one_hour(1);
   ..
}
Run Code Online (Sandbox Code Playgroud)

换句话说,constexpr ctor是否意味着没有任何运行时开销?

Ali*_*Ali 8

constexpr ctor是否意味着没有任何运行时开销?

如有疑问,可随时查看; 例如:

#include <chrono>

template <long Long>
class dummy { };

int main() {

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

  dummy<one_hour.count()> d; 
}
Run Code Online (Sandbox Code Playgroud)

它编译的意思one_hour 是编译时常量,因此没有任何运行时开销.