0

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.

CrSe
  • 328
  • 1
  • 2
  • 10

1 Answers1

1

To give this question some conclusion: Yes, it generally fine to delete the object like you propose. However, please mind the following caveats, that have already been pointed out in the comments:

  • Make sure to initialize test to nullptr in the constructor of the singleton. Otherwise you might end up trying to delete a random memory address. (Some programmer dude)
  • You don't need to check for nullptr in the destructor. Deleting a nullptr is generally safe and won't do anything. (Massimiliano Janes and here)
  • It is probably possible to use a smart pointer in your case, which would be preferable. (Some programmer dude, Massimiliano Janes)
Knoep
  • 858
  • 6
  • 13