0

I have a singleton that needs to be initialized at the start of the program and it will live on until the end of the program. As is usual in this pattern, a function initializing the singleton creates a static pointer member to itself that is returned from the get() method. My usual C++ instinct tells me that if something is initialized with new in a constructor, it should be deleted in a destructor always.

I do feel that my intuition is correct for the simple fact that if I instinctively remember to always delete what I allocate with no exception, I will never forget it when it is actually necessary. But that is a personal coding preference and, I admit, quite a weak argument.

If I were performing code review and had to convince someone that not deleting this allocated memory can lead to potential error later on, how could I argument my case? Or is my intuition wrong and it does actually come down to personal coding preferences?


As a concrete example: the singleton I'm writing is a class that wraps OpenGL calls 1:1, so the client code can use unoptimized calls that are later optimized inside the singleton class - for example if I need to create 100 buffers, I can create them one by one in client code and if the profiler shows this causes a bottleneck, the singleton can create them in minimal possible calls without changes to client call. I'd appreciate if the answers were possibly general and not fixated on this specific example.

2 Answers2

2

If you have a style rule that permits exceptions, then it can't be enforced mechanically, and humans have to verify that it fits a permitted exception, and will have to continue to verify that as the codebase changes. If instead you permit no exceptions, the style rule can be enforced mechanically, and no-one has to verify exceptional cases.

Caleth
  • 12,190
2

The rule for singletons is: They are created automatically the first time they are needed, and they live as long as the program is running. You never call a constructor. You never call a destructor. In C++ a singleton cannot be a static class instance because the runtime will try to destruct them. Especially in a multithreaded environment some thread might be using the singleton.

gnasher729
  • 49,096