Introduction: This is the basis of C + + object memory allocation, to prevent forgetting.
See how a class is constructed when it contains other classes.
#include <iostream>using namespacestd;classobject{ Public: Object () {cout<<"Object:"<<Endl; } ~Object () {cout<<"~object ."<<Endl; }};classcontainer{ Public: Container () {cout<<"Container ...."<<Endl; } ~Container () {cout<<"~container ..."<<Endl; }Private: Object obj_;};intMainvoid) {Container C; return 0;}
Control+f5
Command-line results:
The construction order constructs the containment relation from inside out, and the destruction is the opposite.
To change the constructor, let's see if it has anything to do with initializing the list.
1#include <iostream>2 using namespacestd;3 4 5 classObject6 {7 Public:8Object (intnum): num_ (num)9 {Tencout <<"Object:"<< num_ <<"..."<<Endl; One } A~Object () - { -cout <<"Object:"<< num_ <<"..."<<Endl; the } - Private: - intnum_; - }; + - + A classContainer at { - Public: -Container (intnum1=0,intNum2=0): obj1_ (NUM1), obj2_ (num2) - { -cout <<"Container ...."<<Endl; - } in~Container () - { tocout <<"~container ..."<<Endl; + } - Private: the Object obj1_; * Object obj2_; $ };Panax Notoginseng - intMainvoid) the { +Container C (Ten, -); A return 0; the}
Printing results:
We'll swap the initialization list in the order.
#include <iostream>using namespacestd;classobject{ Public: Object (intnum): num_ (num) {cout<<"Object:"<< num_ <<"..."<<Endl; } ~Object () {cout<<"Object:"<< num_ <<"..."<<Endl; }Private: intnum_;};classcontainer{ Public: Container (intNUM1 =0,intnum2 =0): Obj2_ (num2), obj1_ (NUM1)//The order has been swapped{cout<<"Container ...."<<Endl; } ~Container () {cout<<"~container ..."<<Endl; }Private: Object obj1_; Object obj2_;};intMainvoid) {Container C (Ten, -); return 0;}
Printing results:
So the conclusion is:
The construction order is only related to the order in which the member objects are defined, and their memory is determined from the beginning and is not related to the initialization list
As long as obj1_ is defined in front of obj2_, the construction order must be constructed obj1_ first;
C + + Learning Path: A detailed and initialized list of constructor functions