构造函数初始化列表执行顺序与委托构造函数 [英] constructor initialization list execution order with delegated constructors

查看:323
本文介绍了构造函数初始化列表执行顺序与委托构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个棘手的C ++问题:当你有一个委托构造函数的构造函数初始化列表,什么是列表执行顺序?

I have a tricky C++ question: When you have a constructor initialization list with delegated constructors, what is the list execution order?

这里有两个冲突的标准规则:

1.)构造函数初始化列表不是由列表顺序而是由项目的声明顺序执行。

2.)构造函数初始化列表中的委托构造函数总是得到在执行母构造函数之前调用。

There exist two conflicting standard rules here:
1.) The constructor initialization list gets executed NOT by the list order but by the declaration order of the items.
2.) Delegated constructors in the constructor initialization list always get called before the "mother constructor" is executed.

哪个规则优越? (因为构造函数也是类项)
为什么这很重要:假设委托的构造函数重新插入已由母构造函数初始化的项目,反之亦然。

Which rule is superior? (since a constructor is a class item too) Why this is important: assume the delegated constructor re-inits an item already initialized by the "mother constructor" or vice versa.

推荐答案

§12.6.2/ 6说

§12.6.2/6 says


-initializer-id 指定构造函数的类
它将是唯一的 mem-initializer ...一旦目标构造函数返回,
委托构造函数被执行。

If a mem-initializer-id designates the constructor’s class, it shall be the only mem-initializer... Once the target constructor returns, the body of the delegating constructor is executed.

所以没有冲突,因为你不能在委托构造函数之前初始化任何东西。委托构造函数只需调用该构造函数,目标构造函数的初始化器列表运行,目标构造函数运行,然后主构造函数运行。

So there's no conflict, since you can't initialise anything before you delegate a constructor. Delegating a constructor simply calls that constructor, the target constructor's initialiser list is run, the target constructor runs, and then the principal constructor runs.

这篇关于构造函数初始化列表执行顺序与委托构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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