Wednesday, October 25, 2006

How not to use the boost singleton class

This is an odd and frustrating warning I was seeing while using the templated singleton class which comes with the boost C++ libraries while compiling under Visual Studio 2005. I used the following code to define a class which would be controlling a thread. It worked, but I was scared by the warning.



template< class T > class MySingleton : public boost::detail::thread::singleton < T >
{
};

class MyPayloadThread : public MySingleton< class MyPayload >
{

};



1>c:\src\hdrs\MySingleton.h(133) : warning C4624: 'MySingleton < T > ' : destructor could not be generated because a base class destructor is inaccessible
1> with
1> [
1> T=MyPayload
1> ]
1> c:\src\MySingleton.cpp(16) : see reference to class template instantiation 'MySingleTon < T > ' being compiled
1> with
1> [
1> T=MyPayload
1> ]


I did a lot of googling and couldn't find a direct answer to how I was supposed to give access to the singleton's private destructor. Then I had an epiphany about how I was supposed to use this class. The proper usage is:


typedef boost::detail::thread::singleton < class MyPayload > MyPayloadThread;

In retrospect, it's obvious that I couldn't sub-class singleton, I had to make use of it as a pure template.
 
Google+