C++ - 全局静态对象和局部静态对象的构造函数调用是否不同?

标签 c++ constructor static

这里有一个相同的问题:When exactly is constructor of static local object called?

但它只提到局部静态对象,所以我想为全局静态对象再添加一个案例。

假设我们有 2 个这样的示例代码:

考试 1. 本地静态 ==========

class Mix {
Mix() { //the ctor code }
};

Mix& globalFunction()
{
static Mix gMix; // when its ctor execute ?
return gMix;
}

考试 2. 全局静态 ==========

class Mix {
Mix() { //the ctor code }
static MyClass MReen; // when its ctor execute ?
};

//initialization static var
MyClass Mix::MReen = 0 ;
  • 上述 2 个静态对象的“构造函数代码”何时执行?
  • g++(在 Linux 上运行)和 VC++ 编译器有何不同?

谢谢

最佳答案

我尝试再次测试来自 Adam Pierce 的代码 here ,又增加了两种情况:类中的静态变量和POD类型。我的编译器是 g++ 4.8.1,在 Windows 操作系统 (MinGW-32) 中。 结果是类中的静态变量与全局变量相同。它的构造函数将在进入主函数之前被调用。

  • 结论(针对g++,Windows环境):

    1. 全局变量类中的静态成员:在进入ma​​in函数之前调用构造函数(1).
    2. 局部静态变量:构造函数只在第一次执行到它的声明时被调用。
    3. 如果局部静态变量是POD类型,那么在进入ma​​in函数之前也会初始化(1)。 POD 类型示例:static int number = 10;

(1):正确的状态应该是:“在调用同一翻译单元的任何函数之前”。但是,为了简单起见,如下例所示,然后是主要函数。

包含

#include < string>

using namespace std;

class test
{
public:
   test(const char *name)
            : _name(name)
    {
            cout << _name << " created" << endl;
    }

    ~test()
    {
            cout << _name << " destroyed" << endl;
    }

    string _name;
    static test t; // static member
 };
test test::t("static in class");

test t("global variable");

void f()
{
    static  test t("static variable");
    static int num = 10 ; // POD type, init before enter main function

    test t2("Local variable");
    cout << "Function executed" << endl;
}

int main()
{
    test t("local to main");
    cout << "Program start" << endl;
    f();
    cout << "Program end" << endl;
    return 0;
 }

结果:

static in class created
global variable created
local to main created
Program start
static variable created
Local variable created
Function executed
Local variable destroyed
Program end
local to main destroyed
static variable destroyed
global variable destroyed
static in class destroyed

有人在 Linux 环境中测试过吗?

关于C++ - 全局静态对象和局部静态对象的构造函数调用是否不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20309141/

相关文章:

python - django在static子文件夹中找不到静态文件

java - 静态成员需要特殊的同步块(synchronized block)吗?

c++ - gtkmm 按钮着色

c++ - Visual Studio 2010 本地机器项目特定属性

c++ - 在 Lemon 图形库中使用 Dijkstra 算法

c# - 为什么不能创建抽象类实例但可以调用其构造函数?

c++ - 快速而肮脏的方式来分析你的代码

javascript - 如果不重新分配构造函数,我们如何在函数上使用 'new'

c++ - C++ 什么时候调用作为类成员的对象的构造函数?

c# - 长期静态页面缓存