gpt4 book ai didi

构造函数中的 C++ 单例

转载 作者:行者123 更新时间:2023-11-30 01:42:00 25 4
gpt4 key购买 nike

这可能吗?

class A {
static A *instance = NULL;

public:
A () {
if (instance) {
this = instance;
} else {
instance = this;
}
}
}

是否有内存泄漏?

我需要重载 new 运算符吗?

最佳答案

没有。忽视你的编译器错误,你的类将无法工作。

@Galik has provided invaluable sources了解您实际想要构建单例的方式。但是让我们看看你的。

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;

无论如何,这并不能阻止您构建多个。

关于构造函数中的 C++ 单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40336727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com