C ++初始化字段直接与默认构造函数中的初始化列表进行比较 [英] C++ Initialising fields directly vs initialisation list in default constructor

查看:88
本文介绍了C ++初始化字段直接与默认构造函数中的初始化列表进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这段代码之间是否有区别:

  Foo类{私人的:int a = 0;上市:Foo(){}} 

并且:

  Foo类{私人的:诠释上市:Foo():a(0){}} 

如果是这样,哪个应该是首选?我知道使用初始化程序列表比在构造函数主体中进行分配更可取,但是初始化程序列表与直接在字段声明中进行初始化(至少对于原始类型,在这里是这种情况)呢?

此外,下面是什么情况:

  Foo类{私人的:int a = 0;上市:Foo(){}Foo(int i):a(i){}} 

调用非默认构造函数时:是将"a"初始化两次,先设置为0,然后设置为"i",还是直接设置为"i"?

解决方案

来自 cppreference-非静态数据成员

成员初始化
1)在构造函数的成员初始化器列表中.
2)通过默认成员初始化程序,该成员初始化程序只是成员声明中包含的大括号或等于初始值设定项,如果在成员初始化程序列表中省略了该成员,则使用该初始值设定项.

如果成员具有默认的成员初始值设定项,并且还出现在构造函数的成员初始化列表中,则默认成员初始值设定项将被忽略.


总而言之,两个初始化器都是等效的,并且可以执行它们应该做的事情.

如果我仍然使用默认构造函数,或者所有或大多数构造函数会将成员初始化为相同的值,我将首选默认成员初始化程序.

  Foo类{私人的:int a = 0;}; 

但是,如果所有构造函数将成员初始化为某个不同的值,则使用默认成员初始化器的意义就不那么明显了,那么在各个构造函数中进行显式初始化将更加清楚

  Foo类{私人的:诠释上市:Foo():a(3){}Foo(int i):a(i){}}; 

I'd like to know if there is a difference between this code:

class Foo{
 private:
    int a = 0;
 public:
    Foo(){}
}

And:

class Foo{
 private:
    int a;
 public:
    Foo(): a(0) {}
}

And, if so, which should be preferred? I know it's preferable to use an initialiser list than assigning in the constructor body, but what about initialiser list vs directly initialising in field declaration (for primitive types, at least, as is the case here)?

Also, what of the case below:

class Foo{
 private:
   int a = 0;
 public:
   Foo(){}
   Foo(int i): a(i) {}
}

When the non-default constructor is called: is "a" initialised twice, first to 0 then to "i", or directly to "i"?

解决方案

From cppreference - Non-static data members

Member initialization
1) In the member initializer list of the constructor.
2) Through a default member initializer, which is simply a brace or equals initializer included in the member declaration, which is used if the member is omitted in the member initializer list.

If a member has a default member initializer and also appears in the member initialization list in a constructor, the default member initializer is ignored.


To conclude, both initializers are equivalent and do what they are supposed to do.

I would prefer the default member initializer, if I'd use the default constructor anyway, or if all or most constructors would initialize the member to the same value.

class Foo {
private:
    int a = 0;
};

If all constructors initialize the member to some different value however, using the default member initializer makes less sense, and then an explicit initialization in the respective constructors would be more clear

class Foo {
private:
    int a;
public:
    Foo() : a(3) {}
    Foo(int i) : a(i) {}
};

这篇关于C ++初始化字段直接与默认构造函数中的初始化列表进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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