Valentin
Valentin

Reputation: 1158

Pros and cons of constexpr class members

Compare these two approaches:

// MyClass.hpp
class MyClass
{
  static constexpr char* const FOO = "bar";
};

vs

// MyClass.hpp
class MyClass
{
  static const char* const FOO;
};

// MyClass.cpp
const char* const MyClass::FOO = "bar";

Which one is preferable? I'd imagine that in the second case the "bar" string only gets allocated once, while in the first case it gets allocated once per every .cpp that includes my header. Am I correct? Are there any other points to take into account?

Upvotes: 3

Views: 573

Answers (1)

super
super

Reputation: 12968

The first version is only possible since c++17. It works because all static member variables declared constexpr are implicitly inline.

Multiple definitions are allowed (in separate compilation units) but when linked there will be only 1. So your assumption that it gets allocated once in every .cpp file is not correct.

Which one is preferable could depend. I would choose the first option if I know I'm not gonna change it ever, or very seldom.

If I need to change it, it could cause all .cpp files that #include it to have to recompile, and then it would be better to have it separated in a .cpp file.

Upvotes: 1

Related Questions