为什么需要初始化列表

/****************************************************
# File        : main.cpp
# Author      : lucasysfeng
# Revision    : 2014-10-13 17:04:43
# Description :
****************************************************/
#include <iostream>
using namespace std;

class A
{
public:
    A() { cout << "A constructor" << endl;  }
    ~A() { cout << "A destructor" << endl; }
    A(const A&) { cout << "A copy" << endl; }
    A& operator=(const A) { cout << "A assign" << endl; return *this; }
};

class B
{
public:
    B() { cout << "B constructor" << endl;  }
    // B(const A a) { _a = a; cout << "B constructor with arg" << endl;  }
    B(const A a) : _a(a) { cout << "B constructor with arg" << endl;  }
    ~B() { cout << "B destructor" << endl; }
    B(const B&) { cout << "B copy" << endl; }
    B& operator=(const B) { cout << "B assign" << endl; return *this;}
private:
    A _a;
};

int main(int argc, char** argv)
{
    A a;
    B b(a);

    return 0;
}

  

一般构造函数可以对数据成员赋值,那为什么需要初始化列表

举一个例子就可反证,有的数据成员并不能通过赋值进行初始化,因此初始化列表是必要的。

Effective C++

1.有些情况下必须用初始化——特别是const和引用数据成员只能用初始化,不能被赋值。

2.成员初始化列表的效率比赋值的效率高。

(在构造函数实现中赋值,需要调用构造函数和赋值构造函数;而用成员初始化列表只需

调用拷贝构造函数。)

下面程序错误:
#include <iostream>
using namespace std;

class Test {
private:
	const int a;
public:
	Test() {a = 0;}  //error,不能对const数据成员初始化。
};

int main()
{
	return 0;
}



下面程序正确:

#include <iostream>

using namespace std;

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

int main()
{
	return 0;
}



原文地址:https://www.cnblogs.com/helloweworld/p/2830205.html