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

时间:2013-12-01 05:45:05

标签: c++ constructor static

这里有一个相同的问题: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 ;
  • 何时执行上述2个静态对象的“构造函数代码”?
  • g ++(在Linux上运行)和VC ++编译器之间有何不同?

由于

2 个答案:

答案 0 :(得分:4)

我尝试在here再次测试来自 Adam Pierce 的代码,并添加了两个案例:类中的静态变量和POD类型。我的编译器是g ++ 4.8.1,在Windows操作系统(MinGW-32)中。 结果是类中的静态变量与全局变量一样。在进入main函数之前将调用它的构造函数。

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

    1. 全局变量类中的静态成员:在输入函数 (1)之前调用构造函数 即可。
    2. 本地静态变量:构造函数仅在第一次执行到达声明时被调用。
    3. 如果本地静态变量是POD类型,那么在进入功能 (1) 。 POD类型示例: static int number = 10;

(1):正确的状态应为:“在调用来自同一翻译单元的任何函数之前”。但是,简单来说,如下例所示,然后它是功能。

包括<的iostream>

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

答案 1 :(得分:2)

  1. 在函数中声明的局部静态变量在第一次调用函数之前初始化。您可以在此处阅读有关C ++标准的这些方面的更多信息https://stackoverflow.com/a/58804/747050
  2. 全局静态变量在main()之前初始化,但如果您有多个文件,即使在一个编译器中也不会保证订单。以下是相关答案:http://www.parashift.com/c++-faq/static-init-order.htmlCan the compiler deal with the initialization order of static variables correctly if there is dependency?

    P.S。您可以使用一个技巧保证const static的顺序:

    int YourClass::YourStaticVar()
    {
        static const int value = 0;
        return value;
    }