1. object initialization in the same compilation unit.
Class PhoneNumber {.....};
Class Info
{
Public:
Info (const std: string name, const std: string address, const std: list <PhoneNumber> phonenum): m_Name (name), m_Address (address ), m_PhoneNum (phonenum)
{}
Private:
Std: string m_Name;
Std: list <PhoneNumber>
Std: string m_Address;
};
(1 ). note that if you assign values one by one to the corresponding data members using the value assignment method, this is not initialization, but a value assignment. In this case, the constructor assigns values twice, the parameter is also transferred once, so this will lead to low efficiency.
(2) Pay attention to the initialization sequence of data members. It is initialized according to the declared sequence of data members in the class, and has nothing to do with the order in the initialization list you wrote !!
(3 ). if there are multiple constructors and there are many identical data members between them, you can call the common private member function Init (), !!
2. if the object is in different compilation units, if you want to use another object in different compilation units in a non-local static object, at this time, we cannot guarantee that this object has been initialized before it is used. In fact, the initialization sequence of objects in different compilation units is uncertain. In this way, we use the Singleton mode of designe pattern to solve the problem, that is, moving each non-local static object to its own exclusive function (this object is declared as static ), this type of function returns a reference pointing to the objects it contains. When you use these objects, instead of directly involving these objects, the local static object is called.
Eg1:
Class FileSystem // file system class
{
Public:
..........
Std: size_t numDisk () const;
};
FileSystem tfs;
Assume that the customer creates a class for managing system files
Class Directory
{
Directory (params );
};
Direcoty: Directory (params)
{
Std: size_t disks = tfs. numDisks (); // the tfs object used at this time may not have been initialized, so there is a large Vulnerability
}
Therefore, we use the following method to solve this problem:
Class FileSystem {...}; // the same class as above
FileSystem & tfs ()
{
Static FileSystem fs;
Return fs;
}
Class Directory {...} // same as above
Directory & DirecTemp ()
{
Static Directory dirtemp;
Return dirtemp;
}
From Cql_liliang's Blog