interview
advanced-c
C 中如何实现一个单例模式

C++ 进阶面试题, C++ 中如何实现一个单例模式?

C++ 进阶面试题, C++ 中如何实现一个单例模式?

QA

Step 1

Q:: C++ 中如何实现一个单例模式?

A:: 单例模式是一种设计模式,旨在确保一个类只有一个实例,并提供全局访问点。在 C++ 中,通常通过私有构造函数、私有拷贝构造函数、私有赋值操作符以及一个静态方法来实现。示例如下:

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

通过以上代码,Singleton 类只能创建一个实例,并且可以通过 getInstance 方法访问该实例。

Step 2

Q:: 如何实现线程安全的单例模式?

A:: 在多线程环境下,单例模式的实现需要考虑线程安全问题。可以使用以下几种方式确保线程安全: 1. **双重检查锁定(Double-Checked Locking)**: 使用互斥锁(如 std::mutex)来确保在创建实例时的线程安全,但只在必要时锁定。

 
class Singleton {
private:
    static Singleton* instance;
    static std::mutex mtx;
    Singleton() {};
public:
    static Singleton* getInstance() {
        if (instance == nullptr) {
            std::lock_guard<std::mutex> lock(mtx);
            if (instance == nullptr) {
                instance = new Singleton();
            }
        }
        return instance;
    }
};
Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mtx;
 

2. 使用 std::call_once: C++11 引入的 std::call_once 可以确保某段代码只被执行一次,这使得单例模式的实现更加简洁。

 
class Singleton {
private:
    static std::once_flag initFlag;
    static Singleton* instance;
    Singleton() {};
public:
    static Singleton* getInstance() {
        std::call_once(initFlag, []() {
            instance = new Singleton();
        });
        return instance;
    }
};
Singleton* Singleton::instance = nullptr;
std::once_flag Singleton::initFlag;
 

Step 3

Q:: 如何在 C++ 中实现一个懒汉式单例和饿汉式单例?

A:: 懒汉式单例和饿汉式单例是单例模式的两种实现方式: 1. 懒汉式单例:实例在第一次使用时创建。

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

2. 饿汉式单例:在类加载时实例就被创建。

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

用途

单例模式在实际生产环境中非常常见,特别是当需要确保某个类只有一个实例时,例如数据库连接池、线程池、配置管理器、日志系统等。面试中考察单例模式的实现,不仅可以验证候选人对设计模式的理解,还能考察他们在多线程环境下的编程能力,以及如何高效地使用 C`++` 语言特性来解决问题。\n

相关问题

🦆
C++ 中的设计模式有哪些?

设计模式是解决软件设计中常见问题的一种方法论。C++ 中常用的设计模式包括:单例模式、工厂模式、观察者模式、策略模式、适配器模式等。每种模式都有其特定的应用场景和实现方式。

🦆
C++11 新特性对单例模式的实现有何帮助?

C++11 引入了许多新特性,如 std::mutexstd::call_oncenullptr,这些特性使得单例模式的实现更加安全和简洁。std::call_once 特别适合于确保某段代码仅执行一次,这在实现线程安全的单例模式时非常有用。

🦆
如何避免单例模式的缺陷?

单例模式在某些情况下可能会导致代码过于耦合、难以测试或扩展。可以通过以下方式缓解这些问题: 1. 使用依赖注入减少耦合。 2. 将单例模式的使用范围限制在局部。 3. 在需要时,通过接口或基类为单例类提供替代实现。