Providing the simple implementation of a Singleton class below. It is possible for anybody to call the destructor as long as s/he has the reference to the singleInstance
.
class SomeClass {
public: /** Singleton **/
static SomeClass &instance() {
static SomeClass singleInstance;
return singleInstance;
};
private:
SomeClass() = default;
SomeClass(const SomeClass&) = delete;
SomeClass &operator=(const SomeClass&) = delete;
};
To prevent such a nonsense operation, should we declare the destructor of Singleton classes in a private context?
class SomeClass {
// ... same above
private:
~SomeClass() {}
};
The problem exists also for the heap-allocated Singleton instances. Consider the implementation below.
class SomeClass {
public: /** Singleton **/
static SomeClass &instance() {
static SomeClass *singleInstance = nullptr;
if(!singleInstance) {
singleInstance = new SomeClass;
}
return *singleInstance;
};
private:
SomeClass() = default;
SomeClass(const SomeClass&) = delete;
SomeClass &operator=(const SomeClass&) = delete;
// ~SomeClass() {}
};
int main()
{
SomeClass *const ptr = &SomeClass::instance();
delete ptr; // Compiles if destructor isn't private and vice versa
return 0;
}