为什么我更喜欢使用成员初始化列表? [英] Why should I prefer to use member initialization lists?

查看:84
本文介绍了为什么我更喜欢使用成员初始化列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偏爱在构造函数中使用成员初始化列表...但是我早已忘记了其背后的原因...

I'm partial to using member initialization lists with my constructors... but I've long since forgotten the reasons behind this...

您使用构造函数中的成员初始化列表?如果是这样,为什么?如果没有,为什么不呢?

Do you use member initialization lists in your constructors? If so, why? If not, why not?

推荐答案

用于 POD 类成员,这没有什么区别,这只是样式问题。对于属于类的类成员,则可以避免不必要地调用默认构造函数。考虑:

For POD class members, it makes no difference, it's just a matter of style. For class members which are classes, then it avoids an unnecessary call to a default constructor. Consider:

class A
{
public:
    A() { x = 0; }
    A(int x_) { x = x_; }
    int x;
};

class B
{
public:
    B()
    {
        a.x = 3;
    }
private:
    A a;
};

在这种情况下, B 的构造函数将调用 A 的默认构造函数,然后将 ax 初始化为3。更好的方法是使用 B 的构造函数直接在初始化列表中调用 A 的构造函数:

In this case, the constructor for B will call the default constructor for A, and then initialize a.x to 3. A better way would be for B's constructor to directly call A's constructor in the initializer list:

B()
  : a(3)
{
}

这只会调用 A A(int)构造函数,而不是其默认构造函数。在此示例中,差异可以忽略不计,但是想像一下,如果您愿意 A 的默认构造函数做更多的事情,例如分配内存或打开文件。

This would only call A's A(int) constructor and not its default constructor. In this example, the difference is negligible, but imagine if you will that A's default constructor did more, such as allocating memory or opening files. You wouldn't want to do that unnecessarily.

此外,如果类没有默认构造函数,或者您具有 const 成员变量,则必须使用初始化列表:

Furthermore, if a class doesn't have a default constructor, or you have a const member variable, you must use an initializer list:

class A
{
public:
    A(int x_) { x = x_; }
    int x;
};

class B
{
public:
    B() : a(3), y(2)  // 'a' and 'y' MUST be initialized in an initializer list;
    {                 // it is an error not to do so
    }
private:
    A a;
    const int y;
};

这篇关于为什么我更喜欢使用成员初始化列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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