-3
class m
{
    public:
    static m* get()
    {
        static m s;
        m* p= NULL;
        p = &s;
        return p;
    }
    private:
    m();
    ~m();
}
songyuanyao
  • 147,421
  • 15
  • 261
  • 354
  • 8
    Why do *you* want to call the destructor? Your compiler will do it for you. – Rakete1111 Jun 26 '18 at 07:40
  • 4
    Just adding the mandatory [Why are singletons bad?](https://stackoverflow.com/a/138012/4711812) – muXXmit2X Jun 26 '18 at 07:41
  • cause i need the output printed by my destructor in main code – hanisha nandigam Jun 26 '18 at 07:46
  • @hanishanandigam you need to exit your program to see `~m()` being called. – marcinj Jun 26 '18 at 08:07
  • 2
    To be honest destroying a singleton sounds like the worst design decision ever. The point about singletons is that all the code, everywhere can access the singleton whenever it wants. If part of the code destroys it, how are you going to let every other part of the code know it is no longer safe to ue it? It means (at the very least) everywhere you use the singleton you also have to add a check to make sure it has not been destroyed already. Checks can get forgotten. I suspect whatever you are trying to do overall probably has a better solution. – Galik Jun 26 '18 at 08:11
  • This doesn't address the question, but there is no need here to separate initialization and assignment. Replace `m* p = NULL; p = &s;` with `m* p = &s;`. And you could make `p` static, too. Or get rid of `p` entirely, and just `return &s;`. – Pete Becker Jun 26 '18 at 11:35

2 Answers2

4

Assuming that you're wondering how to destroy a singleton instance (there are very few situations where explicitly calling the destructor is appropriate), you implement your singleton as a thing that can be destroyed.
(Whether this is really a singleton can probably be debated, but that discussion doesn't belong here.)

This means that you need to create it dynamically.
Something like this:

class m
{
public:
    static m* get()
    {
        if (!s) s = new m;
        return s;
    }

    static void destroy() { delete s; s = nullptr; }

    m(const m&) = delete;
    m& operator=(const m&) = delete;

private:
    m();
    ~m();
    static m* s = nullptr;
};

(Insert mandatory warning that this variant isn't thread safe at all here.)

molbdnilo
  • 55,783
  • 3
  • 31
  • 71
1

The simplest answer would be exit(0). Singletons live for the duration of your program, so you have to end the program.

MSalters
  • 159,923
  • 8
  • 140
  • 320