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++11 新特性对单例模式的实现有何帮助?▷
🦆
如何避免单例模式的缺陷?▷