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.

9
  • 1
    You should probably initialize test in the constructor. Otherwise if the user never calls SetTest then GetTest will return an invalid (and most likely non-null) pointer, and the destructor will attempt to delete something which wasn't allocated. Commented Oct 9, 2017 at 11:28
  • 3
    Strictly speaking, a singleton is anti-pattern. And anything you need it to own is probably indicative of greater anti-patterns in your code. Commented Oct 9, 2017 at 11:29
  • 1
    With a custom deleter it's still possible to use smart pointers. Commented Oct 9, 2017 at 11:43
  • 1
    shared_ptr<> does not need a complete type ( but shared_ptr dtor does ), no need of a custom deleter Commented Oct 9, 2017 at 12:50
  • 1
    moreover, "if(test) delete test;" is useless ( you can delete a null pointer ) ... Commented Oct 9, 2017 at 12:51

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.