Harry Boy
Harry Boy

Reputation: 4747

How to properly cleanup a static class in c++

I need to have a singleton class as I need to initialise some variables only once. I have a problem when I can't to clean up the class as it is crashing. Here is a cut down version of my class:

#include "stdafx.h"
#include <iostream>

class MyClass
{
public:
    MyClass();
    virtual ~MyClass();

    static MyClass& Instance();
    void DoSomething();
};

MyClass::MyClass()
{
    std::cout<<"MyClass constructor"<<std::endl;
    //initialise some stuff here
}

MyClass::~MyClass()
{
    std::cout<<"MyClass destructor"<<std::endl;
    //clean up some stuff here
}

MyClass& MyClass::Instance()
{
    static MyClass _instance;
    return _instance;
}

void MyClass::DoSomething()
{
    std::cout<<"Do something"<<std::endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
    MyClass& myClass = MyClass::Instance();
    myClass.DoSomething();

    delete &myClass;

    return 0;
}

When I call the delete &myClass the destructor gets called and then it blows up like so:

enter image description here

I have investigated and I think that I shouldn't be calling delete on an object that has not been created using new. Is this correct??

Is the answer simply don't use any delete and let the destructor be called automatically when it goes out of scope (When main returns)?

Upvotes: 1

Views: 987

Answers (3)

utnapistim
utnapistim

Reputation: 27365

Your error is due to the delete (as mentioned by others).

I need to have a singleton class as I need to initialise some variables only once.

No, you really (really, really) don't. Singletons solve the problem of centralizing values/settings, while introducing hidden state, tightening module coupling, hiding module dependencies and rendering code untestable.

Consider using dependency injection instead.

Upvotes: 1

WAQ
WAQ

Reputation: 2616

When the static object goes out of scope, they will be deleted automatically, so dont bother calling delete on a static object and you should be fine

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254431

I shouldn't be calling delete on an object that has not been created using new.

Absolutely. It's a static object, which will be destroyed automatically at the end of the program. There's no need (and no way) to destroy it yourself.

(Note that, being static, it's not destroyed when it goes out of scope when Instance() returns. Instead it's destroyed at the end of the program, after returning from main() or calling exit()).

Upvotes: 6

Related Questions