Simple implementation in C ++ singleton

C ++ implement singletons (a)

Implementation

1. The constructor, destructor privatization, thus ensuring that the class can not be created outside the class instance of class calling the constructor, by the process can only be created inside the class definition;

2. Within the class definition static, pointing to the class pointer variable ptr, responsible for keeping instances created class and outside the class is initialized nullptr;

3. Define static instantiating objects within a class, and a method for the destruction of objects. Constructor, if ptris nullptrthen performed on the heap to create an object, or directly back to the pointer; method of object destruction, if the pointer is not null, then the destructor for recovering the application stack space.

code show as below:

class Singleton {
public:
    static Singleton* getInstance() {
        if(nullptr == ptr) {
            cout << "getInstance()" << endl;
            ptr = new Singleton() //调用构造函数对对象进行实例化
        }
        return ptr; //返回指向该对象的指针
    }
    
    static void destory() {
        if(ptr) {
            delete ptr; // 回收堆空间
            ptr = nullptr;  // 防止野指针
        }
    }
    
private:
    Singleton() { //构造函数
        cout << "Singleton()" << endl;
    }
    
    ~Singleton() { //析构函数
        cout << "~Singleton()" << endl;
    }
    static Singleton* ptr;  //指向该对象的指针
};

Singleton* Singleton::ptr = nullptr; //静态对象在类外进行初始化

Guess you like

Origin www.cnblogs.com/zhhz9706/p/12150142.html