什么時候一個空的類將變得不空?答案是當(dāng) C++ 得到了它。假如你自己不聲明一個拷貝構(gòu)造函數(shù),一個拷貝賦值運(yùn)算符和一個析構(gòu)函數(shù),編譯器就會為這些東西聲明一個它自己的版本。而且,假如你自己連一個構(gòu)造函數(shù)都沒有聲明,編譯器就會為你聲明一個缺省構(gòu)造函數(shù)。所有這些函數(shù)都被聲明為 public 和 inline(參見 Item 30)。作為結(jié)果,假如你寫
class NamedObject { public: // this ctor no longer takes a const name, because nameValue // is now a reference-to-non-const string. The char* constructor // is gone, because we must have a string to refer to.
NamedObject(std::string& name, const T& value); ... // as above, assume no // operator= is declared private: std::string& nameValue; // this is now a reference const T objectValue; // this is now const }; 現(xiàn)在,考慮這里會發(fā)生什么:
NamedObject<int> p(newDog, 2); // when I originally wrote this, our // dog Persephone was about to // have her second birthday NamedObject<int> s(oldDog, 36); // the family dog Satch (from my // childhood) would be 36 if she // were still alive
p = s; // what should happen to // the data members in p? 賦值之前,p.nameValue 和 s.nameValue 都引向 string 對象,但并非同一個。那個賦值對 p.nameValue 產(chǎn)生了什么影響呢?賦值之后,p.nameValue 所引向的字符串是否就是 s.nameValue 所引向的那一個呢,也就是說,引用本身被改變了?假如是這樣,就違反了常規(guī),因為 C++ 并沒有提供使一個引用引向另一個對象的方法。換一種思路,是不是 p.nameValue 所引向的那個 string 對象被改變了,從而保持指針或引用還是指向那個對象,也就是說,賦值并沒有直接影響對象?這是編譯器產(chǎn)生的拷貝賦值運(yùn)算符應(yīng)該做的事情嗎?