WEBINAR: On-demand webcast
How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >
One code change was required in the Instance() method. This is due to the fact that the auto_ptr class does not provide a set() method for its already provided get() method. It does, however, provide an assignment operator. For this reason it was necessary to introduce a temporary variable "tmp" into the Instance method and construct it with a pointer to the allocated memory. This pointer is then assigned to the already-constructed sm_inst auto_ptr which takes over management of the pointer resource. Apart from that, the class functions in much the same way as the previous version, so what is there to choose between them?
The original required a wrapper class with a nested class and a couple of methods defined to ensure a leak-free implementation. It also relied on the fact that we would use the wrapped class and not the "bare" class itself. If this is kept to then the first implementation is fine. However, for each of your singleton classes you would need some way of duplicating the resource protection provided by the nested InstPtr class and also an agreement that all clients only use the wrapped version.
The standard C++ library auto_ptr<> class supports the
"resource acquisition is initialisation" idiom. For more information
on this, section 14.4 in Bjarne Stroustrup's book
"The C++ Programming Language"
may prove enlightening.
The auto_ptr class is a class which "manages" a pointer assigned to it and which deallocates the pointer when the auto_ptr class goes out of scope. This is precisely the functionality we wish to provide for our singleton class.
The 208 bytes leak may be attributable to Microsoft's implementation of the C++ standard library for iostream (see A leak-free singleton class for further details). The LCMapStringW problems are due to the C run-time libraries and there's not much we can do about those either. Perhaps the most interesting thing to note is that the singleton class doesn't leak - just like the original.
Resource Management, section 14.4, page 364, "The C++ Programming Language 3rd Edition" by Bjarne Stroustrup, Publishers: Addison-Wesley, ISBN 0-201-88954-4