Re: singleton question
ben chang wrote:
i'm hacking at some code originally written for VC++, trying to port to
linux GCC 4. the linker returns multiple-definition errors with a
singleton object, which i guess is not a problem in visual c++. i'll try
to excerpt the relevant parts without posting all the source files (it's
the maya exporter for the Ogre 3D engine).
there's a pretty standard-looking Singleton template, and in a file called
"materialSet.h" we have a class using it:
/////
namespace OgreMayaExporter
{
class MaterialSet : public Singleton<MaterialSet>
{
(nothing unusual in here, so i won't bore you... )
};
template<> MaterialSet Singleton<MaterialSet>::ms_Singleton=0;
The above line defines Singleton<MaterialSet>::ms_Singleton. If this is in a
header and that header is included in multiple files, you'll get multiple
definitions of that object.
this declaration is complicated enough that it's a bit hard to wrap my
head around, but isn't this essentially repeatedly declaring a global
(within the namespace) variable, which is what Singletons are supposed to
avoid?
It's repeatedly _defining_ the very same namespace-level variable, which any
program is supposed to avoid. Put the definition into an implementation
file, not a header.