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]), ...
{
}
}
Am I right in assuming that the initialization will happen exactly in the order I've given in the ctor? If not, what if m_nDataLength's initialization happens after m_pData's?
While the initialization in your example does happen in the order you want, it's not for the reason you assume: Initialization happens in the order of the data members declaration in the class definition. The reason for this is that the destructor must destroy the members in backward order not matter which constructor was used to create the object. For that, a constructor-independent way of defining the construction order must be used.
That means that, if instead of
class myClass
{
private:
...
int m_nDataLength;
boost::shared_array<int> m_pData;
someone would change your code to
class myClass
{
private:
...
boost::shared_array<int> m_pData;
int m_nDataLength;
then the code would have a bug.
My advice is:
Something like this should do:
class myClass
{
private:
...
int m_nDataLength; // Note: Declaration order
boost::shared_array<int> m_pData; // matters here!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With