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.
unique_ptr
instead of raw pointers for the static variable. That way, you get automatic destruction. Raw-pointers are only good for two things: representing nullable references to non-owned data, or as a low level implementation detail for implementing smart pointers.new