Singleton pattern destructor C++
c++, destructor, singleton, valgrind
Solution
Stopwords::~Stopwords() {
delete instance;
}
This is the destructor for instances of the class. You probably intended this function to be called when the program ends, as though it were a kind of 'static' destructor, but that's not what this is.
So your destructor for instances of Stopwords initiates destruction of Stopwords instances; You've got an infinite loop here, which you never enter. If you do get into this loop then the program will probably just crash.
There's a simpler way to do singletons: Instead of keeping the instances as a static class member that you allocate manually, simply keep it as a static function variable. C++ will manage creating and destroying it for you.
class Stopwords {
public:
static Stopwords &getInstance() {
static Stopwords instance;
return instance;
}
~Stopwords();
std::map<std::string,short> getMap();
private:
Stopwords();
std::map<std::string,short> diccionario;
};
Also, you should mark member functions that don't need to modify the class as `const`:
std::map<std::string,short> getMap() const;
Problem
i have this singleton pattern and it runs ok. But when i execute my program with valgrind to check memory leaks, it seems that the instance is never destroyed. Where is my mistake? Header ``` class Stopwords { private: static Stopwords* instance; std::map<std::string,short> diccionario; private: Stopwords(); public: ~Stopwords(); public: static Stopwords* getInstance(); std::map<std::string,short> getMap(); }; ``` .cpp ``` Stopwords* Stopwords::instance = NULL; Stopwords::Stopwords() { diccionario = map<string,short>(); char nombre_archivo[] = "stopwords/stopwords.txt"; ifstream archivo; archivo.open(nombre_archivo); string stopword; while(getline(archivo,stopword,',')) { diccionario[stopword] = 1; } archivo.close(); } Stopwords::~Stopwords() { delete instance; } Stopwords* Stopwords::getInstance() { if (instance == NULL) { instance = new Stopwords (); } return instance; } map<string,short> Stopwords::getMap(){ return diccionario; } ``` It's not relevant but in the initialization, i read a bunch of words from a file and i save them in a map instance. Thanks