template<class T>
class SafeMember {
public:
T _; /* short name for convenience */
SafeMember(T const& obj) : _(obj) { }
};
इस तरह उपयोग किया: जब आप एक "SafeMember<int> age
" सदस्य जोड़ सकते हैं और भूल जाते हैं अपनी कॉपी-निर्माता अद्यतन करने के लिए
class Student {
public:
Student(string surname, Color hairColor)
: surname(surname)
, hairColor(hairColor) { }
Student(Student const& other)
: surname(other.surname)
, hairColor(other.hairColor) { }
Student& operator=(Student const& other) {
surname = other.surname;
hairColor = other.hairColor;
return *this;
}
string getSurname() const { return surname._; }
// The foo._ syntax is better than implicit conversion because
// it lets us call member functions, like substr in this example:
bool isSlavic() const {return surname._.substr(surname._.size()-2)=="ev";}
void dyeHair(Color newColor) { hairColor = newColor; }
private:
SafeMember<string> surname;
SafeMember<Color> hairColor;
};
अब, संकलन सहायक के असफल हो जायेगी।
और "नो-ऑप" संकेत के लिए, डेवलपर "प्रारंभ (0)" जैसे प्रारंभकर्ता को जोड़ देगा।
नोट: यह आपके ऑपरेटर =() या धारावाहिक() फ़ंक्शन को बिट-रॉट से केवल संरक्षक नहीं बचाता है। उम्मीद है कि, यह पर्याप्त होना चाहिए: एक बार जब आप रचनाकारों से अपना चूक देखते हैं, तो आपको शायद अन्य कार्यों के माध्यम से भी जाना याद रहेगा।
स्रोत
2009-03-17 20:44:34
"सभी सदस्यों रास्ता wrapp नहीं"। –
खैर, सेफमेम्बर उन्हें लपेटने में काफी आसान बनाता है। मुझे लगता है कि ओपी उन्हें _manually_ लपेटने से बचना चाहता है। –
क्षमा करें, लेकिन यह नए सदस्य चर के साथ काम करता है .. मुझे केवल डिफ़ॉल्ट कन्स्ट्रक्टर के लिए अनुस्मारक मिला है। – bayda