C Singleton tasarım deseni
Son zamanlarda C Singleton/uygulama gerçekleşme tasarım deseni çarptı ettim . Bu gibi görünüyordu (gerçek hayattan örnek bunu benimsemiştir):
// a lot of methods are omitted here
class Singleton
{
public:
static Singleton* getInstance( );
~Singleton( );
private:
Singleton( );
static Singleton* instance;
};
Bu bildirinin örneğini alan öbek başladığı olmadığını anlıyoruz. Bir bellek ayırma anlamına gelir. Benim için tamamen belirsiz tam olarak ne bellek ayırmanın ne zaman? Yoksa hata ve bellek sızıntısı? Uygulamada bir sorun yok gibi görünüyor.
Benim asıl soru, nasıl doğru şekilde uygulanması mı?
CEVAP
Bir tembel garantili imha singleton ile değerlendirilmesi için basit bir tasarım için bu makaleye bakın
Can any one provide me a sample of Singleton in c ?
Klasik tembel ve doğru olarak değerlendirilen singleton yok.
class S
{
public:
static S& getInstance()
{
static S instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
private:
S() {}; // Constructor? (the {} brackets) are needed here.
// C 03
// ========
// Dont forget to declare these two. You want to make sure they
// are unacceptable otherwise you may accidentally get copies of
// your singleton appearing.
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
// C 11
// =======
// We can use the better technique of deleting the methods
// we don't want.
S(S const&) = delete;
void operator=(S const&) = delete;
};
Bir singleton kullanmak için bu makaleye bakın: (sık değil)
Singleton: How should it be used
Başa çıkmak için nasıl başlatılması amacıyla ilgili ve bu iki makalesine bakın:
Static variables initialisation order
Finding C static initialization order problems
Bakın bu makalede açıklayan ömür:
What is the lifetime of a static variable in a C function?
Diş çekme etkileri tekiz: bazı anlatılır bu makaleye bakın
Singleton instance declared as static variable of GetInstance method
Kilitleme kontrol açıklıyor bu makaleye bakın C çalışmaz :
What are all the common undefined behaviours that a C programmer should know about?
PHP5 içinde Singleton tasarım deseni o...
C Singleton tasarım deseni...
Singleton tasarım deseni vs Singleton ...
PHP Fabrika Tasarım Deseni nedir?...
Statik sınıf ve singleton deseni arası...