初始化列表中的依赖关系 [英] Dependencies in Initialization Lists

查看:210
本文介绍了初始化列表中的依赖关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个行为是否明确定义?

  class Foo 
{
int A,B;

public:

Foo(int Bar):B(Bar),A(B + 123)
{
}
} ;

int main()
{
Foo MyFoo(0);
return 0;
}


解决方案

A 将首先被初始化(它是类定义中的第一个),并且它使用未初始化的 B



类成员按照它们在类定义中出现的顺序进行初始化,而不考虑它们在初始化列表中的顺序。实际上,成员定义顺序与初始化列表顺序不匹配是不好的做法。



如果你的实例 Foo 发生有静态持续时间,如 Foo f(0); int main(){} ,行为是很好定义的。具有静态持续时间的对象在任何其他初始化发生之前被初始化;在这种情况下,运行构造函数时, A B 将为0。之后,行为是一样的:第一 A 然后 B ,给出 A 值<123, B Bar p>

Is this behavior well-defined?

class Foo
{
    int A, B;

    public:

    Foo(int Bar): B(Bar), A(B + 123)
    {
    }
};

int main()
{
    Foo MyFoo(0);
    return 0;
}

解决方案

No, it's undefined. A will be initialized first (it's first in the class definition), and it uses uninitialized B.

Class members are initialized in the order they appear in the class definition, irrespective of their order in the initialization list. Indeed, it is bad practice to mismatch the member definition order with the initialization list order.

If your instance of Foo happened to have static duration, like in Foo f(0); int main(){}, the behavior is well-defined. Objects with static duration are zero-initialized before any other initialization takes place; in that case, A and B will be 0 when the constructor is run. After that, though, the behavior is the same: first A then B, giving A a value of 123 and B a value of Bar (still ugly).

这篇关于初始化列表中的依赖关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆