Home > Software engineering >  Does header initialization break RAII?
Does header initialization break RAII?

Time:07-27

Consider the following C header:

#include "OtherThing.h"

class Thing
{
public:
    Thing(); //ctor

private:
    OtherThing my_var_{};
};

Is the private var my_var_ still managed according to RAII, or does its lifetime exceed the scope of Thing in any way? I searched for a clear answer for a good while, but either formed my question poorly or didn't know how to read what was given.

CodePudding user response:

Is the private var my_var_ still managed according to RAII, or does its lifetime exceed the scope of Thing in any way?

The data member my_var_ is a non-static data member and is associated with a particular instance of class Thing. More importantly, it's lifetime can never exceed the lifetime of the associated Thing object.

When a given Thing object goes out of scope, it's data members are also destroyed. Basically, a Thing object includes its data members so logically when the Thing object is destroyed the data members will also be destroyed.


Also note that technically the lifetime of an object with a constructor doesn't begin until the execution of the constructor has completed. So the lifetime of the class members is slightly longer than lifetime of the containing object as pointer out by @M.M

CodePudding user response:

OtherThing my_var_{}; is syntactic sugar to a adding ma_var_{} in the member initialization list of every constructor, including those generated by the compiler.

So it's the same as writing

Thing() : my_var_{} { } //ctor
  • Related