【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++ 编译的结果

 

 

 

 

小结

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值