Skip to content

cpp_static_singleton

ShenYj edited this page Apr 15, 2024 · 3 revisions

static单例模式

  1. 将构造函数、析构函数私有化, 外界将不允许通过构造函数初始化对象
  2. 定义一个私有的static成员变量,指向唯一的哪个单例对象
  3. 提供一个公共的访问的访问单例对象的接口
  • 示例

    class Rocket {
    private:
        Rocket() { }
        /// 防止外界通过实例调用 delete 释放堆空间
        ~Rocket() { }
        static Rocket *ms_rocket;
    
    public:
        static Rocket *sharedRocket() { 
            /// 这里要考虑多线程安全
            if (ms_rocket == NULL) {
                ms_rocket = new Rocket();
            }
            return ms_rocket;
        }
    
        static void deleteRocket() {
            /// 这里要考虑多现成安全
            if (ms_rocket != NULL) {
                /// 将指针所指向的堆空间回收掉, 但是指针所指向堆空间依然有值,所以仍然需要清空置为 NULL,否则容易出现野指针
                delete ms_rocket;
                ms_rocket = NULL;
            }
        }
    }
    
    Rocket *Rocket::ms_rocket = NULL;
    
    int main() {
        
        Rocket *p = Rocket::sharedRocket();
    
        return 0;
    }
  • 利用 运算符重载 进一步完善单例

    class Rocket {
    private:
        /// 利用重载禁用掉赋值操作
        void operator=(const Rocket &rocket) 「 」
        /// 将宝贝构造也私有化
        Rocket(const Rocket rocket) { }
    
        Rocket() { }
        /// 防止外界通过实例调用 delete 释放堆空间
        ~Rocket() { }
        static Rocket *ms_rocket;
    
    public:
        static Rocket *sharedRocket() { 
            /// 这里要考虑多线程安全
            if (ms_rocket == NULL) {
                ms_rocket = new Rocket();
            }
            return ms_rocket;
        }
    
        static void deleteRocket() {
            /// 这里要考虑多现成安全
            if (ms_rocket != NULL) {
                /// 将指针所指向的堆空间回收掉, 但是指针所指向堆空间依然有值,所以仍然需要清空置为 NULL,否则容易出现野指针
                delete ms_rocket;
                ms_rocket = NULL;
            }
        }
    }
    
    Rocket *Rocket::ms_rocket = NULL;
    
    int main() {
        
        Rocket *p1 = Rocket::sharedRocket();
        Rocket *p2 = Rocket::sharedRocket();
        /// 自己赋值给自己,废操作, 应该通过重写操作符禁用掉 = 函数
        //*p1 = *p2;
    
        /// 拷贝构造 ,同理将宝贝构造也私有化
        //Rocket *p3 = new Rocket(*p2);
    
        return 0;
    }

Getting Started

Social

Clone this wiki locally