21xrx.com
2025-04-14 07:20:10 Monday
文章检索 我的文章 写文章
C++实现单例模式
2023-06-29 04:38:26 深夜i     10     0
C++ 单例模式 实现

单例模式是一种常用的设计模式,在系统中仅存在一个实例对象,可以方便地进行全局访问。在C++中,我们可以通过一些简单的代码实现单例模式。

首先,我们需要定义一个单例类。此类必须将其默认构造函数私有化,以防止其他类创建其实例。它还应该声明一个静态的指向自己唯一实例的指针。例如:

class Singleton {
private:
  Singleton() {}
  static Singleton* instance;
public:
  static Singleton* getInstance() {
    if (instance == nullptr) {
      instance = new Singleton();
    }
    return instance;
  }
};

在上面的代码中,我们将默认构造函数设为私有,使其他类无法创建其实例。我们还声明了一个静态的指向自己唯一实例的指针,命名为"instance"。getInstance()是获取单例实例的方法,在方法中我们检查实例是否存在,如果不存在则创建它。

除此之外,还有一些需要注意的地方。

首先,我们需要在程序退出时手动销毁单例实例,否则可能会导致内存泄漏。实现方式是在单例类中定义一个静态方法,用于销毁单例实例。例如:

class Singleton {
private:
  Singleton() {}
  static Singleton* instance;
public:
  static Singleton* getInstance() {
    if (instance == nullptr) {
      instance = new Singleton();
    }
    return instance;
  }
  static void destroyInstance() {
    if (instance != nullptr)
      delete instance;
      instance = nullptr;
    
  }
};

其次,在多线程环境中,需要考虑线程安全。如果多个线程同时调用getInstance()方法,可能会创建多个实例,导致不符合单例模式的要求。可以使用线程锁或者双重检查锁机制来保证线程安全。例如:

class Singleton {
private:
  Singleton() {}
  static Singleton* instance;
  static std::mutex mtx; // 加锁对象
public:
  static Singleton* getInstance() {
    if (instance == nullptr) {
      std::lock_guard<std::mutex> lock(mtx); // 加锁
      if (instance == nullptr) {
        instance = new Singleton();
      }
    }
    return instance;
  }
  static void destroyInstance() {
    if (instance != nullptr)
      delete instance;
      instance = nullptr;
    
  }
};
std::mutex Singleton::mtx; // 初始化互斥锁

在上面的代码中,我们使用了std::mutex来加锁,保证同一时间只有一个线程可以访问getInstance()方法。

以上是C++实现单例模式的基本方式,可以根据实际情况进行修改和改进。

  
  

评论区

请求出错了