我应该使用初始化列表或在我的C++构造函数中执行赋值吗?

nXq*_*Xqd 9 c++ constructor initializer variable-assignment

class Node
{
public:

    Node *parent; // used during the search to record the parent of successor nodes
    Node *child; // used after the search for the application to view the search in reverse

    float g; // cost of this node + it's predecessors
    float h; // heuristic estimate of distance to goal
    float f; // sum of cumulative cost of predecessors and self and heuristic

    Node() :
            parent( 0 ),
            child( 0 ),
            g( 0.0f ),
            h( 0.0f ),
            f( 0.0f )
    {
    }

    UserState m_UserState;
};
Run Code Online (Sandbox Code Playgroud)

为什么我们应该使用构造函数

    Node() :
            parent( 0 ),
            child( 0 ),
            g( 0.0f ),
            h( 0.0f ),
            f( 0.0f )
    {
    }
Run Code Online (Sandbox Code Playgroud)

代替

    Node()
    {
        parent = null;
        child = null;
        g = 0.0f;
        h = 0.0f;
        f = 0.0f;
    }
Run Code Online (Sandbox Code Playgroud)

谢谢 :)

Fre*_*Foo 14

对于普通旧数据(POD),这几乎没什么好处,但是一旦你开始使用引用或编写类,它就会产生影响:

class Foo {
    Bar bar;

  public:
    // construct bar from x
    Foo(int x) : bar(x) { }
};
Run Code Online (Sandbox Code Playgroud)

Foo::Foo(int x)
{
    // bar is default-constructed; how do we "re-construct" it from x?
    bar = x;  // requires operator=(int) on bar; even if that's available,
              // time is wasted default-constructing bar
}
Run Code Online (Sandbox Code Playgroud)

有时候,你甚至没有办法在构造一个对象时"重新构建"它,因为一个类可能不支持setter或者operator=.const成员当然不能"重建"或重置:

class FooWithConstBar {
    const Bar bar;

  public:
    Foo(int x) {
        // bar is cast in stone for the lifetime of this Foo object
    }
};
Run Code Online (Sandbox Code Playgroud)

编辑:感谢@Vitus指出引用的问题.

  • 此外,引用不能在构造函数体中分配,必须在初始化列表中初始化. (3认同)

rjn*_*son 6

由于在某些情况下您实际需要或出于性能原因使用初始化列表初始化成员,因此您应该保持一致并始终使用它.

需要使用初始化列表的示例是聚合没有默认构造函数或者有const成员时(是,非常见但允许).

应该(但不是被迫)使用初始化列表的示例是当您有一个聚合对象并且以下几点有效时:

  • 聚合具有默认构造函数.
  • 您需要使用非默认值设置对象.
  • 聚合具有一个构造函数,允许您设置所需的非默认值.

那么 - 你为什么不用它?