0

Let's say I have this constructor :

MyClass::MyClass()
 : m_foo(new Foo())
 , m_bar(new Bar(m_foo))
{
}

Is it safe/legit to use a member like this to initialize other members ?

Thanks

Placid
  • 1
  • 4
  • This example is not safe regardless because the second one could throw and leak the memory of the first. – chris Sep 06 '19 at 16:27
  • @chris Depends on what `m_foo` is. – Lightness Races in Orbit Sep 06 '19 at 16:56
  • @LightnessRacesinOrbit, Yes. However, it's quite abnormal to use `new` in example code like this, which points to a different issue. `m_foo` could be a smart pointer or something, but that'd be an extra complication irrelevant to the question, so it doesn't make much sense. That was my reasoning. – chris Sep 06 '19 at 17:23
  • @chris I'm just saying that we have no idea whether this example is safe or not. – Lightness Races in Orbit Sep 07 '19 at 16:05

1 Answers1

2

It depends on the order in which m_foo and m_bar appear in the class definition. Since data members are initialized in order of definition, the code above is safe only if m_foo appears before m_bar.

Compilers usually warn about order mismatches between the constructor initialization list and class definition.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416