什么时候调用全局对象的构造函数?

时间:2019-09-16 20:18:06

标签: c++

我写的一些代码:

#include <iostream>

class Number
{
    int n;
public:
    Number(int n)
    {
        std::cout << "Constructed object: " << n << std::endl;
        this->n = n;
    }
};

Number b = 2; //when does this ctor get called?

int main()
{
    Number a = 4;
}

输出:

Constructed object: 2
Constructed object: 4

何时调用全局对象的构造函数?是在执行main之前?

2 个答案:

答案 0 :(得分:3)

  

何时调用全局对象的构造函数?在main执行之前?

从本质上讲,是的。在翻译单元中,对象按照出现的顺序构建。在翻译单元中,顺序是不确定的。

物体的破坏顺序与构造相反。

对于gcc(我想也是clang),另请参见:How exactly does __attribute__((constructor)) work?

答案 1 :(得分:0)

是的,全局对象的构造函数在main()之前被调用

有关其他信息: 在这里,我列出了何时调用构造函数来调用不同类型的对象,例如全局,局部,静态局部,动态

1)对于已编写程序的全局对象

2)对于非静态本地对象,当执行到达声明对象的位置时,调用构造函数

using namespace std; 
class Test 
{ 
public: 
Test(); 
}; 

Test::Test() { 
    cout << "Constructor Called \n"; 
} 

void fun() { 
Test t1; 
} 

int main() { 
    cout << "Before fun() called\n"; 
    fun(); 
    cout << "After fun() called\n"; 
    return 0; 
} 
/* OUTPUT: 
    Before fun() called 
    Constructor Called 
    After fun() called 
*/

对于本地静态对象,第一次(并且只有第一次)执行到达声明对象的位置。 3)类作用域:创建对象时,编译器确保调用其所有子对象(其成员和继承的对象)的构造函数。如果成员具有默认构造函数或没有参数的构造函数,则将自动调用这些构造函数,否则可以使用“初始化列表”来调用参数化的构造函数。

// PROGRAM 1: Constrcuctor without any parameter 
#include<iostream> 
using namespace std; 

class A 
{ 
public: 
A(); 
}; 

A::A() { 
    cout << "A's Constructor Called \n"; 
} 

class B 
{ 
A t1; 
public: 
B(); 
}; 

B::B() { 
    cout << "B's Constructor Called \n"; 
} 

int main() { 
    B b; 
    return 0; 
} 
/* OUTPUT: 
    A's Constructor Called 
    B's Constructor Called 
*/