构造函数中的c++单例

C++ singleton in constructor

本文关键字:单例 c++ 构造函数      更新时间:2023-10-16

这可能吗?

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;

您不能为这个

赋值