C ++ initialization list and memory allocation

Is the following valid?

class myClass { private: ... int m_nDataLength; boost::shared_array<int> m_pData; ... public: myClass(): ..., m_nDataLength(10), m_pData(new int[m_nDataLength]), ... { } } 

Do I really assume that initialization will happen in the exact order that I gave in ctor? If not, what if m_nDataLength initializes after m_pData?

+4
source share
3 answers

As long as the initialization in your example is done in the order you want, this is not for the reason you assume: Initialization occurs in the order of the declaration of the data members in the class definition. . The reason is that the destructor must destroy the members in the reverse order, no matter which constructor was used to create the object. For this, it is necessary to use a constructor-independent way of determining the construction order.

This means that if instead

 class myClass { private: ... int m_nDataLength; boost::shared_array<int> m_pData; 

someone will change your code to

 class myClass { private: ... boost::shared_array<int> m_pData; int m_nDataLength; 

then the code will have an error.

My advice:

  • Write your constructors so that the initialization order does not matter.
  • If you cannot do this (note: for me this has happened less than 5 times in the last decade), make it very clear at the time the data members are declared.

Something like this should do:

 class myClass { private: ... int m_nDataLength; // Note: Declaration order boost::shared_array<int> m_pData; // matters here! 
+10
source

initialization will initialize the fields in order in the class, therefore: if you change

 private: ... int m_nDataLength; boost::shared_array<int> m_pData; 

a

 private: ... boost::shared_array<int> m_pData; int m_nDataLength; 

it will not work. The constructor does not apply order.

+9
source

No, initialization for members of a class occurs in the order in which members appear in the class definition. If a member appears in the initializer list, then it controls the expression used to initialize this element (even if it uses an element that has not yet been initialized), but where it appears in the initialization list does not affect its initialization.

+5
source

All Articles