C++ 静态成员变量 嵌套类分配回收内存

来源:网络时间:2012-04-06 17:05:13

  嵌套类分配回收内存

  #include <stdio.h>

  #include <assert.h>

  class CA

  {

  public:

  inline static CA *GetInstance(void)

  {

  assert(m_instance != NULL);

  return m_instance;

  }

  void Print(void)

  {

  puts("主类的Print函数运行看看");

  }

  class Garbage//用来分配内存的嵌套类

  {

  public:

  Garbage(int i, int j)

  {

  printf("Garbage分配内存开始:%d %d\n", i, j);

  m_instance = new CA(123123, 234234234);

  }

  ~Garbage()

  {

  delete m_instance;

  puts("Garbage收拾残局结束");

  }

  };

  static Garbage m_garbage;

  protected:

  friend class Garbage;

  CA(int i, int j){printf("主类构造函数运行: %d %d\n", i, j);}

  ~CA(){printf("主类析构函数运行,结束了哦\n");}

  static CA *m_instance;

  };

  CA *CA::m_instance = NULL;

  CA::Garbage CA::m_garbage(2, 3);

  int main()

  {

  CA *cmb = CA::GetInstance();

  cmb->Print();

  return 0;

  }

文章内容来源于网络,不代表本站立场,若侵犯到您的权益,可联系我们删除。(本站为非盈利性质网站) 联系邮箱:9145908@qq.com