构造函数中的c++单例
C++ singleton in constructor
这可能吗?
class A {
static A *instance = NULL;
public:
A () {
if (instance) {
this = instance;
} else {
instance = this;
}
}
}
它有泄漏内存吗?
我需要重载new
算子吗?
No。忽略编译器错误,你的类将无法工作。
@Galik提供了宝贵的资源,告诉你如何构造一个单例。但让我们看看你的。
class A {
static A *instance = NULL; // NULL isn't even a thing, but assuming you mean nullptr you can't assign a static like this
public:
A () {
if (instance) {
this = instance; // this can't be assigned
} else {
instance = this; // this is correct
}
}
};
它会给你以下内容:
class A {
static A *instance;
public:
A () {
// if there's no instance, this is the one we'll use
if (!instance) {
instance = this;
}
}
};
A* A::instance = nullptr;
这并不妨碍您构建多个
不可能。如果公开并调用构造函数,将不可避免地创建一个A
的新对象。最优雅和广泛使用的c++单例类实现使用静态方法返回单个静态实例,同时隐藏构造函数(例如使private
可访问)。
下面是一个例子:
class A {
private:
static A *instance_; // use nullptr since C++11
A() {}
public:
static A& instance() {
if (!instance_)
instance_ = new A();
return *instance_;
}
};
A* A::instance_ = nullptr;
您不能为这个
相关文章:
- 为什么在单例中,检查类==空?
- C++ 实现模板单例类时出现链接错误
- 在类中存储单例的指针
- C++中的单例实现在调用 getInstance 函数时不会产生相同的类实例
- 具有非默认构造函数的单例类
- 使用 std::call_once 实现类似单例的功能
- 为什么单例使用指针而不是引用?
- 提升单例池release_memory vs purge_memory
- 具有 QObject 继承的单例 - Qt
- 单例类析构函数无法清理 (SDL_Quit) MinGW
- C++单例,不会为此文档加载任何符号
- 使用 CRTP 实现单例
- C++单例模板类使我的程序崩溃
- 初学者C++线程安全单例设计
- 派生类是单例是否是一种好的做法
- _CrtIsValidHeapPointer(块)错误在应用单例-帕特恩后退出主窗口时引发
- 在这种单例实施中,是否可以对两个商店重新排序?
- 这是MSVC 2013中具有共享PTR的单例的正确实现吗?
- C++ 单例实现 迈耶与call_once
- 如何析构单例实例,或者为什么以下代码适用于析构函数?