C++中的局部静态对象

来源:互联网 发布:c语言指针例题 编辑:程序博客网 时间:2024/06/06 08:41

一个简单的class T

class T
{
public:
  T()
  {
   value = 0x12345678;
  }
  ~T()
  {
   value = 0;
  }
  int value;
};

加上一个简单的foo函数,里面定义了一个静态局部对象:

void foo()
{
    static T t;
}

 

编译器展开后,实际上等同我们定义了

char tMemory[sizeof(T)];
int  tInit = 0;
void tFree()
{
   ((T*)tMemory)->~T();
}

void foo()
{
  if(!tInit)
  {
     tInit = 1;
     new (tMemory) T();
     atexit(tFree);
  }
}

 

原创粉丝点击