quetzalfir quetzalfir - 1 month ago 15
C++ Question

C++ singleton in constructor

Is this possible?

class A {
static A *instance = NULL;

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


Does it have leak memory?

Do I need to oveload
new
operator?

Tas Tas
Answer

No. Overlooking your compiler errors, your class won't work.

@Galik has provided invaluable sources for how you'd actually want to construct a singleton. But let's look at yours.

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
        }
    }
};

Which would give you the following:

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;

Which doesn't stop you from constructing more than one anyway.

Comments