lundi 9 octobre 2017

Delete objects from a singleton class

I want to create a simple Singleton class in C++ which contains pointers to other types.

The singleton will become the owner over that pointer at some point.

So it's this a good way to delete the object of type Test and release it's memory on Singleton destructor?.

 class Test{...};
 class Singleton
 {
    public:
    static Singleton& getInstance()
    {
        static std::unique_ptr<Singleton> instance(new Singleton());
        return *instance.get();
    }

    void SetTest(Test* test);
    Test* GetTest() const;
    ...
    private:
      Singleton(){}
      ~Singleton(){ if(test) delete test;} // ??
      Test* test;
     ...
 };

PS: I can't use smart pointers for the Test object.

Aucun commentaire:

Enregistrer un commentaire