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

2024-03-18

这里有一个同样的问题:静态局部对象的构造函数到底什么时候被调用? https://stackoverflow.com/questions/3063027/when-exactly-is-constructor-of-static-local-object-called

但它只提到本地静态对象,所以我想为全局静态对象添加一种情况。

假设我们有两个示例代码,如下所示:

考试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 ;
  • 上面两个静态对象的“构造函数代码”到底是什么时候被执行的?
  • g++(在 Linux 上运行)和 VC++ 编译器有何不同?

Thanks


我尝试再次测试代码亚当·皮尔斯 at here https://stackoverflow.com/questions/55510/when-do-function-level-static-variables-get-allocated-initialized,并增加了两种情况:类中的静态变量和POD类型。我的编译器是 g++ 4.8.1,在 Windows 操作系统(MinGW-32)中。 结果是类中的静态变量与全局变量的处理方式相同。它的构造函数将在进入 main 函数之前被调用。

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

    1. 全局变量 and 类中的静态成员:在进入之前调用构造函数main功能(1).
    2. 局部静态变量:构造函数仅在执行第一次到达其声明时才被调用。
    3. If 局部静态变量是POD类型,那么在进入之前也是初始化的main功能(1)。 POD 类型示例:静态 int 数 = 10;

(1):正确的状态应该是:“在调用同一翻译单元的任何函数之前”。然而,为了简单起见,如下例所示,那么它是main功能。

包含

#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;
 }

result:

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 环境下测试过吗?

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++ - 全局静态对象和局部静态对象的构造函数调用不同吗? 的相关文章

随机推荐