quetzalfir
quetzalfir

Reputation: 568

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?

Upvotes: 2

Views: 6797

Answers (3)

Viktor Tóth
Viktor Tóth

Reputation: 499

Not possible. If the constructor is exposed and called, a new object of A is inevitably created. The most elegant and widely used implementations of C++ singleton classes use static methods to return the single static instance, while hiding (e.g. make private accessible) the constructor.

Here's an example:

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;

Upvotes: 2

Tas
Tas

Reputation: 7111

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.

Upvotes: 2

Tony Thomas
Tony Thomas

Reputation: 1005

You cannot assign a value for this

Upvotes: 0

Related Questions