加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 类初始化与构造函数初始化列表的顺序

发布时间:2020-12-16 09:21:40 所属栏目:百科 来源:网络整理
导读:我想在类中初始化一堆成员以保持源文件更清晰.但是,对象采用我只通过构造函数接收的参数,并且可以通过赋值在构造函数初始化列表或构造函数中初始化. (第二种选择肯定不会起作用.)这基本上是这样的情景: 在标题中 class Foo{public: Foo(Pointer * ptr);priv
我想在类中初始化一堆成员以保持源文件更清晰.但是,对象采用我只通过构造函数接收的参数,并且可以通过赋值在构造函数初始化列表或构造函数中初始化. (第二种选择肯定不会起作用.)这基本上是这样的情景:

在标题中

class Foo
{

public:
    Foo(Pointer * ptr);

private:

    Pointer * ptr;
    Member m1{ptr,"SomeText"};
    Member m2{ptr,"SomeOtherText"};
}

在CPP

Foo::Foo(Pointer*ptr) : 
    ptr(ptr) 
{
    // ...
}

现在的问题是:标准是否说明了ptr和m1 / m2之间的初始化顺序?显然,只有在m1和m2之前初始化ptris时,此代码才有效.

解决方法

这一点得到了标准的保证,即非静态数据成员将按照类定义中的声明顺序进行初始化.它们如何初始化(通过默认成员初始化程序或成员初始化程序列表)以及这些初始化程序的顺序无关紧要.

[class.base.init]#13.3

(13.3) – Then,non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).

[?Note: The declaration order is mandated to ensure that base and member subobjects are destroyed in the reverse order of initialization. —?end note?]

这意味着,初始化顺序将始终为ptr – > m1 – >平方米.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读