चीयर्स,सी ++ में स्थिर उदाहरण के माध्यम से सिंगलेट्स - स्रोत में या हेडर फाइलों में?
मैं "उदाहरण से प्रोग्रामिंग खेल ऐ" में कोड के इस खंड में भाग:
/* ------------------ MyClass.h -------------------- */
#ifndef MY_SINGLETON
#define MY_SINGLETON
class MyClass
{
private:
// member data
int m_iNum;
//constructor is private
MyClass(){}
//copy ctor and assignment should be private
MyClass(const MyClass &);
MyClass& operator=(const MyClass &);
public:
//strictly speaking, the destructor of a singleton should be private but some
//compilers have problems with this so I've left them as public in all the
//examples in this book
~MyClass();
//methods
int GetVal()const{return m_iNum;}
static MyClass* Instance();
};
#endif
/* -------------------- MyClass.cpp ------------------- */
//this must reside in the cpp file; otherwise, an instance will be created
//for every file in which the header is included
MyClass* MyClass::Instance()
{
static MyClass instance;
return &instance;
}
मैं लेखक कि स्थिर घोषित चर द्वारा बात-की-तथ्य बयान से उलझन में हूँ शीर्षलेख में किसी फ़ंक्शन के अंदर एकाधिक, अलग स्थैतिक चर instance
घोषित करने का परिणाम होगा। मुझे नहीं लगता कि मैंने इस व्यवहार को getInstance()
फ़ंक्शन के सामान्य कार्यान्वयन में देखा है जिसे मैं नियमित रूप से हेडर में डालता हूं (सिवाय इसके कि मुझे पॉइंटर्स के साथ खेलना और सिंगलटन को पहले उपयोग पर प्रारंभ करना पसंद है)। मैं अपने काम के लिए जीसीसी का उपयोग कर रहा हूं।
तो मानक क्या कहता है? गैर-अनुपालन कंपाइलर्स क्या कहते हैं? क्या लेखक का कथन सही है, और यदि हां, तो क्या आप कुछ कंपाइलर्स नाम दे सकते हैं जो getInstance()
शीर्षलेखों में घोषित किए गए थे तो कई उदाहरण बनाएंगे?
सी ++ में थ्रेड-सुरक्षा के साथ सिंगलटन को कार्यान्वित करने के बारे में एक अच्छी चर्चा इस पेपर में पाई जा सकती है: http://www.aristeia.com/Papers/DDJ%5FJul%5FAug%5F2004%5Frevised .pdf –