Article 4: Determine the object has been initialized before being used

Note three things:

1. Manually initialize a built-in non-member objects

2. Use to initialize all members of the list of members to deal with objects

3. "initialization sequence does not" question to pay attention to their design.

 

Here we focus on the case of the third:

The following tfs will be used in an external file b.cpp, but it is currently not possible to guarantee that the wording used in the b.cpp tfs has been initialized, this will cause problems.

. 1  // AH 
2  class the FileSystem
 . 3  {
 . 4  public :
 . 5      int numDisk () const ;
 . 6  };
 . 7  
. 8  extern the FileSystem FS;     // only declared
 . 9  
10  // a.cpp 
. 11 the FileSystem FS;     // this is defined 
12 is  
13 is  
14  /// B.cpp 
15  class Directory
 16  {
 . 17  public :
 18 is      Directory ( String  the params)
 . 19      {
 20 is          int Disks fs.numDisks = ();     // because a.cpp b.cpp at compile time and does not guarantee the sequence, there may not yet be initialized tfs, where it was used 
21      }
 22 } ;

 

Tfs to declare a function that returns a reference to an object, such b.cpp when to call in, we can ensure fs must be initialized. But here I have a question, why the authors refer to a static variable use of it? Can not is a local variable? or do not use references?

. 1  // AH 
2  class the FileSystem     // defined in the library class 
. 3  {
 . 4  public :
 . 5      int numDisks () const ;
 . 6  };
 . 7  
. 8  // a.cpp 
. 9 the FileSystem & TFS () // write shows TFS () is a global function, not a member function. 
10  {
 11      static the FileSystem FS;     // when C ++ to ensure that local static objects function will be during "the function is called" the "first met the definition of the object type" is initialized. 
12 is      return FS;
 13 is  }
 14  
15  // B.cpp 
16  class Directory
17 {
18 public:
19     Directory(string params)
20     {
21         int  disks = tfs().numDisks();    
22     }
23 };

 

Guess you like

Origin www.cnblogs.com/Stephen-Qin/p/12081549.html