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

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

问题描述

我部分使用成员初始化列表与我的构造函数...但我很久以前忘记了这个...背后的原因

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 initialize 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天全站免登陆