Initialization order with constructors in C ++

When I instantiate an object in C ++ with the following class, I get a segmentation or interrupt error, depending on the order in which member variables are declared. E. g. putting mMemberVar and mAnotherMemberVar after mAnotherCountVar results in segfault. From this list, I removed std :: ofstream from member variables, which caused a segmentation error regardless of its position.

I think that order is not a direct problem, but what do you think might be the reason? This class is part of a huge project, but in this class this is the place where the error first appeared.

class COneClass : public IInterface
{
public:

  COneClass();

  virtual ~COneClass();

  static const unsigned int sStaticVar;
  static const unsigned int sAnotherStaticVar;


private:
  COneClass();
  COneClass(const COneClass& );
  COneClass& operator=(const COneClass& );

  int mMemberVar;
  int mAnotherMemberVar;
  bool mIsActive;
  bool mBoolMemberVar;
  bool mAnotherBoolMemberVar;
  unsigned int mCountVar;
  unsigned int mAnotherCountVar;
};

COneClass::COneClass() :
  mMemberVar(0),
  mAnotherMemberVar(0),
  mIsActive(false), 
  mBoolMemberVar(false),
  mAnotherBoolMemberVar(false),
  mCountVar(sStaticVar),
  mAnotherCountVar(sAnotherStaticVar)
{
}
+3
source share
7 answers

. . : mMemberVar β†’ mAnotherMemberVar β†’ mIsActive β†’ mBoolMemberVar β†’ mAnotherBoolMemberVar β†’ mCountVar β†’ mAnotherCountVar;

+5

, " ", http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.16, mCountVar mAnotherCountVar ?

, .

+5

" " , , ( , ???). , .

+3

. , , , .

, .

- ,

class MyClass//**1: mem-init**
{
private:
long number;
bool on;
public:
MyClass(long n, bool ison) : number(n), on(ison) {}
};

MyClass(long n, bool ison) //2 initialization within constructor body
{
number = n;
on = ison;
}

MyClass. , mem-initialization. mem . , . mem :

  • const
  • -
+3

, . , ? , - .

bool Invariant() const; ( ) assert(Invariant()); . " , " , , .

+2

. , , , REGARDLESS . , , , , . , - :

class MyClass {
public:
    const int member1;
    const int member2;
    MyClass() {
      : member2(0),
      : member1(member2) // ERROR: this runs first because member1 is defined first
                      // member2 not yet constructed; assigns undefined value to member1
    {}
};
+1

, , . - IInterface , - . , -, , .

0

Source: https://habr.com/ru/post/1718802/


All Articles