effective c++ 条款4 make sure that objects are initialized before they are used

1 c++ 类的数据成员的初始化发生在构造函数前

class InitialData
{
    public:
         int data1;
         int data2;
        
         InitialData(int a, int b)
        {
            data1 = a; //this is assignment
            data2 = b; //this is assignment
        }

       /*
       InitialData(int a, int b):data1(a),data2(b) //this is initial
       {}
      */
}

 2 不同cpp文件中的static变量初始化顺序不确定,千万不要互相引用

     比如有个 FileSystem类

class FileSystem
{
  public:
     ...
     int getDiskNum() const;
}
extern FileSystem tfs;//in the hfile, used in the future for some other class

 然后在一个叫global.cpp文件中申明了一个全局 FileSystem tfs;

然后有个Directory类用到tfs

#include "FileSystem.h"

class Directory
{
public:
	Directory()
	{
		int t=tfs.numDisks();
	}
};

 有个人需要用Directory类,于是他申明

Directory tmpDir;这时就出现问题,tmpDir初始化时需要用到tfs,单编译器不能保证在编译tmpDir之前编译tfs,于是就会出现编译错误。

解决方案是采用singleton模式,利用函数得到全局变量

FileSystem& getFileSystem
{
    static FileSystem tfs;
    return tfs;
}

 在Directory要调用tfs时用这个函数

#include "FileSystem.h"

class Directory
{
public:
	Directory()
	{
		int t=getFileSystem();
	}
};

 

  

  

effective c++ 条款4 make sure that objects are initialized before they are used,布布扣,bubuko.com

effective c++ 条款4 make sure that objects are initialized before they are used

上一篇:在JavaScript中重写jQuery对象的方法


下一篇:javascript---BOM