赋值不是初始化

<span style="font-family: Arial, Helvetica, sans-serif;">class PhoneNumber {...};</span>
class ABEntry{
public:
	ABEntry(const std::string& name, const std::string& address, const std::aligned_storage<PhoneNumber>& phones);
private:
	std::string theName;
	std::string theAddress;
	std::aligned_storage<PhoneNumber> thePhones;
	int numTimesConsulted;
};

ABEntry::ABEntry(const std::string& name, const std::string& address, const std::aligned_storage<PhoneNumber>& phones)
{
	theName = name;
	theAddress = address;
	thePhones = phones;
	numTimesConsulted = 0;
}


如上,构造函数实际上是赋值,不属于初始化,初始化发生的时间更早。构造函数初始化较佳的写法为:

ABEntry::ABEntry(const std::string& name, const std::string& address, const std::aligned_storage<PhoneNumber>& phones)
:theName(name), 
theAddress(address),
thePhones(phones),
numTimesConsulted(0)
{
}
使用成员初值列的方法初始化,虽然和赋值的结果相同,但效率更高。

你可能感兴趣的:(赋值不是初始化)