天天看點

effective c++條款04-1

1.為内置類型進行手工初始化,C++不保證會初始化他們,這取決于你用的是C++的哪部分(STL自動初始化,C不會自動初始化)

2.構造函數最好使用成員初始化清單,而最好不要在構造函數本體内進行指派操作,初始化清單列出的成員變量,其順序最好和class聲明時一樣

3.為免除"跨編譯單元之初始化次序"問題,請以local static 對象替代 non-local static變量

第1條好了解,所有的内置類型的變量使用前最好初始化,否則會發生無法預料的錯誤

第2條

先看代碼

#include <windows.h>
#include <iostream>
#include <string>
#include <vector>

class E04
{
	friend ostream& operator<<(ostream out,E04& e04)
	{
		out<<e04.m_text;
	}
public:
	E04():m_text("Hello,world!")
	{
		cout<<"E04對象初始化"<<endl;
	}
	E04(string s):m_text(s){}
	E04(const char* s):m_text(s){}
	const E04& operator=(const E04& other)
	{
		if(this==&other)
			return *this;
		this->m_text=other.m_text;
		return *this;
	}
	~E04(){}
private:
	string m_text;
};

class Player
{
public:
	Player(const std::string& name,const int age,std::vector<int>&scores,E04 e04)
	{
		m_name=name;
		m_age=age;
		m_scores=scores;
		m_e04=e04;
	}
	~Player() {}
private:
	std::string m_name;
	int	m_age;
	std::vector<int> m_scores;
	E04	m_e04;
};

int main()
{
	E04 e04("lilei");
	std::vector<int> scores(10);
	cout<<"開始進行初始化"<<endl;
	Player player("xxx",12,scores,e04);
	system("pause");
	return 0;
}
           
effective c++條款04-1

我們看到E04對象再構造函數進行指派之前先走了一遍預設構造函數

這就是為什麼不推薦在構造函數體内進行指派初始化的原因

将構造函數進行修改

Player(const std::string& name,const int age,std::vector<int>&scores,E04 e04):m_name(name),m_age(age),m_scores(scores),m_e04(e04)
	{
	/*	m_name=name;
		m_age=age;
		m_scores=scores;
		m_e04=e04;*/
	}
           
effective c++條款04-1

(1).我們看到,每個m_e04在初始化的時候再也沒有先經過E04類的預設構造函數

甚至當你自己想主動調用預設構造函數的時候,都可以這麼在初始化清單中寫 m_e04()

(2).還有一點需要注意,初始化清單一定要把所有的成員變量都列全,如果有個自定義類型沒列出來,那問題不大,還有預設構造函數,如果有個内置類型比如int,初始化清單中沒列出,那這個成員變量的值很可能無法預料

(3).const成員(非 static)或者reference一定需要初值,是以隻能使用初始化清單進行初始化

繼續閱讀