Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
694 views
in Technique[技术] by (71.8m points)

c++ - Initializing members with members

This is a problem I come across often. The following examples illustrates it:

struct A {
    int m_SomeNumber;
};

struct B {
    B( A & RequiredObject );
private:
    A & m_RequiredObject;
};

struct C {
    C( );
private:
    A m_ObjectA;
    B m_ObjectB;
};

The implementation of the constructor of C looks something like this:

C::C( )
 : B( m_ObjectA )
{ }

Since the order of initialization is not defined, m_ObjectA might be uninitialized when the constructor of m_ObjectB is called, resulting in undefined behavior. One way to force a certain order of initialization would be to make the members pointers and initialize them in the constructor body, thus forcing the correct order, but this is ugly for several reasons. Is there any way to force a certain initializtion order using the initialization-list of the constructor? If not, do you have any other suggestions how to handle this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since the order of initialization is not defined

On the contrary, it is well-defined. The order of initialization is equal to the order in which the member variables are declared in your class (and that’s regardless of the actual order of the initialization list! It’s therefore a good idea to let the initialization list order match the order of the declarations to avoid nasty surprises).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...