C++中对象构造顺序

2017-10-14  本文已影响0人  nethanhan

单个对象的构造与析构


局部对象


举个🌰:

    int i = 0;
    Test a1 = i;
        
    while( i < 3 )
    {
        Test a2 = ++i;
    }
        
    if( i < 4 )
    {
        Test a = a1;
    }
    else
    {
        Test a(100);
    }

在这段代码里Test类构造顺序是按照程序的执行流依次往下进行。

堆对象


再次举🌰:

    int i = 0;
    Test* a1 = new Test(i); // Test(int i): 0
        
    while( ++i < 10 )
        if( i % 2 )
            new Test(i); // Test(int i): 1, 3, 5, 7, 9
        
    if( i < 4 )
        new Test(*a1);
    else
        new Test(100); // Test(int i): 100

在这段代码中只有执行new时在堆空间分配空间后才执行构造方法。

全局对象


最后举一次🌰:

#include "test.h"

Test t4("t4");

int main()
{
    Test t5("t5");
}

这里的Test是全局对象,那它的构造顺序就不确定,依编译器而定。

上一篇下一篇

猜你喜欢

热点阅读