0

I want to achieve something like this:

class MyTest: public ::testing::Test {
public:
   const int myConstInt     = 23;
}

TEST_F(MyTest, MyTest1) {... use myConstInt ...}

But recollecting from Item 4 of EffectiveCPP, the initialization is not guaranteed in this manner and there is a chance of undefined behavior.

Let's say the above is Method 1.

I can think of two other methods to achieve this:

Method 2: Initializer list of myConstStr using a MyTest constructor.

Method 3: Make it constexpr - since the value is set at compile time I shouldnt face any initialization issues during runtime.

Which would be the correct way to go about this? Also Effective CPP is a relatively old book - Does the discussion of Item 4 still fully apply?

tangy
  • 3,056
  • 2
  • 25
  • 42

2 Answers2

1
   const int myConstInt     = 23;

is a non static data member with a default member initializer https://en.cppreference.com/w/cpp/language/data_members#Member_initialization

There is absolutely no risk that it is undefined behavior.

The initialization is guaranteed

sandwood
  • 2,038
  • 20
  • 38
0

Post discussion on Cpplang slack , found out that the best solution would be to use a static const for any integral/Enum types - can also use static constexpr but this is essentially the same except in C++17 where static constexpr data members can also be inlined.

Additioal useful Reference: constexpr vs. static const: Which one to prefer?

tangy
  • 3,056
  • 2
  • 25
  • 42