如果想第一次使用的时候再初始化,而程序正常退出的时候,再释放资源。那么应该将其放到某个函数中,作为static声明。

#include "Object.h"
#include "Container.h"
#include <iostream>

using namespace std;

static Object sglobal(" static global");
Object global(" global");

void func()
{
 cout << "  In func()" << endl;
 Container cc;
 cout << "  Out func()" << endl;
}

void func2()
{
 cout << "  In func2()" << endl;
 Container cc;
 cout << "  Out func2()" << endl;
}

int main()
{
 cout << "main() begin." << endl;
 Object local(" local");
 func();
 func2();
 //Container cc;
 cout << "main() end." << endl;
 return 0;
}

输出是:

C:\Project\CPP\LearnCpp\debug>InitializationOrder.exe
 static global initializing...
 global initializing...
 object in container initializing...
 global in container initializing...
 static global in container initializing...
main() begin.
 local initializing...
  In func()
 Static In Container Constructor initializing...
 In Container Constructor initializing...
Initializing Container ...
 In Container Constructor releasing...
  Out func()
Releasing Container ...
  In func2()
 In Container Constructor initializing...
Initializing Container ...
 In Container Constructor releasing...
  Out func2()
Releasing Container ...
main() end.
 local releasing...
 Static In Container Constructor releasing...
 static global in container releasing...
 global in container releasing...
 object in container releasing...
 global releasing...
 static global releasing...