공부/C++
Effective C++ 항목 4 : 객체를 사용하기 전에 반드시 그 객체를 초기화하자
털빙이
2022. 5. 7. 23:22
대입과 초기화를 헷갈리지 말자.
class PhoneNumber {};
class ABEntry{
public :
ABEntry(const string& name, const string& address, const list<PhoneNumber>& phones);
private:
string theName;
string the Address;
list<PhoneNumber> thePhones;
int theNum;
};
ABEntry::ABEntry(string& name, string& address, list<PhoneNumber>& phones)
{
theName = name; //요거는 초기화가아니라 대입임..
theAdress = adress;
thePhones = phones;
theNum = 0;
}
c++ 규칙에 의하면 객체는 생성자본문이 실행되기전에 초기화를 해야한다고 명기되어 있다.
위 코드는 이미 초기화를 진행 후, 생성자에 본문에서 대입이 이뤄졌다.
theNum은 초기화가 되었을까? --> 기본타입은 초기화 보장이 되지 않는다.
따라서 초기화를 명시적으로하는방법은 다음과 같다.
ABEntry::ABEntry(string& name, string& address, list<PhoneNumber>& phones)
: theName(name),
theAdress(adress),
thePhones(phones),
theNum(0)
{}
초기화리스트를 의무적으로 사용하는경우
1. 상수
2. 참조자
이유? 상수와 참조자는 대입연산자를 사용할수 없다.