【C++】21.对象的构造顺序

实际开发中,因为对象的构造顺序的问题导致bug很多。

那么C++中的类可以定义多个对象,那对象构造的顺序是怎样的?

局部对象

程序执行流到达对象的定义语句时进行构造。

class Test
{
    int i;
public:
    Test(int i)
    {
        this->i = i;
        cout << "Test(int i) = " << i << endl;
    }

    Test(const Test& t)
    {
        this->i = t.i;
        cout << "Test(const Test& t) = " << this->i << endl;
    }

    int value()
    {
        return i;
    }

};

int main()
{
    int i = 0;
    Test a1 = i;

    while( i < 3)
    {
       Test a2 = ++ i;
    }

    if( i < 4)
    {
       Test a3 = a1;
    }
    else
    {
        Test a3(100);
    }

    return 0;
}

输入结果:

构造的过程中不要使用 goto 语句,会带来灾难性的问题

int main()
{
    int i = 0;
    Test a1 = i;

    while( i < 3)
    {
       Test a2 = ++ i;
    }

goto End;

        Test a3(100);
End:
        a3.value();

    return 0;
}

不同编译器执行的结果不一样,一般的会提示如下错误

堆对象

当程序执行流到达new语句时创建对象,使用new创建对象将自动触发构造函数的调用。

int main()
{
    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
        
    return 0;
}

全局对象

对象的构造顺序是不确定的,不同的编译器使用不同的规则确定构造顺序。

工程上:

如果对象的构造顺序不定,带来的问题是如果全局对象中里面含有其它类,初始化顺序不定会出错。所以应该避免全局对象。

// test.h

#ifndef _TEST_H_
#define _TEST_H_

#include <stdio.h>

class Test
{
public:
    Test(const char* s)
    {
        printf("%s\n", s);
    }
};

#endif

// t1.cpp

#include "test.h"

Test t1("t1");


// t2.cpp

#include "test.h"

Test t2("t2");


// t3.cpp

#include "test.h"

Test t3("t3");

// test.cpp

#include "test.h"

Test t4("t4");

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

Linux 下 g++ 编译的结果

小结

发布了84 篇原创文章 · 获赞 0 · 访问量 772

猜你喜欢

转载自blog.csdn.net/zhabin0607/article/details/103140329