在构造函数初始化器中复制初始化? [英] Copy initialization in constructor initializer?

查看:290
本文介绍了在构造函数初始化器中复制初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我的构造函数初始化器不能使用复制初始化?

Why can't my constructor initializer use copy initialization?

struct S { int a; S(int b) : a(b)  {} }; // direct initialization compiles
struct T { int a; T(int b) : a = b {} }; // copy initialization does not



我很困惑,因为 a(b) a = b 都是表达式(postfix和assignent表达式),我的C ++书[1]说任何任意复杂的表达式。

I am confused because a(b) and a = b are both expressions (postfix and assignent expressions, resp.), and my C++ book [1] says that "An initializer may be any arbitrarily complex expression."

[1] Lippman,Lajoie,Moo。 C ++ Primer,4th ed。 p457。

[1] Lippman, Lajoie, Moo. "C++ Primer, 4th ed." p457.

推荐答案

这不是直接初始化。 T a = b; 称为复制初始化。直接初始化是 T a(1,'foo',false); ,并且在你的构造函数中你会写熟悉的 T

That's not direct initialization. T a = b; is called copy intialization. Direct initialization is T a(1, 'foo', false);, and in your constructor you would write the familiar T(int b) : a(b, 'foo', false) { } to achieve this effect, as you already have in your first example.

相比之下, T a; 称为默认初始化,通过在初始化器列表中保留一个未提及的变量来实现。它的效果是调用类类型上的默认构造函数,并且不对基本类型执行任何初始化(同上数组)。

By contrast, T a; is called default initialization, which you achieve by leaving a variable entirely unmentioned in the initializer list. Its effect is to call the default constructor on class types, and to perform no initialization at all on fundamental types (ditto for arrays).

值初始化可以写为 T(int b):a(){} 。您还可以在 new 表达式中使用值初始化,但是由于烦琐的解析,它们在自动声明中很棘手。

By contrast again, value initialization can be written as T(int b) : a() { }. You can also use value-initialization in new expressions, but they're tricker in automatic declarations due to the vexing parse.

我认为直接,默认和值初始化是C ++ 98/03初始化列表中唯一允许的初始化形式,而C ++ 11在混合中添加了各种口味的统一初始化。

I think direct, default and value initialization are the only permissible forms of initialization in initializer lists in C++98/03, while C++11 adds various flavours of uniform initialization to the mix.

这篇关于在构造函数初始化器中复制初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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