C ++: Undefined instance reference in Singleton class

I'm currently trying to implement a factory as a singleton. I practically used the example of a Singleton template tutorial. Here is the .h file:

namespace oxygen{ class ImpFactory{ public: static boost::shared_ptr<ImpFactory> GetInstance(); private: static boost::shared_ptr<ImpFactory> mInstance; }; 

and here is the .cpp file:

 #include "impfactory.h" using namespace oxygen; using namespace boost; shared_ptr<ImpFactory> ImpFactory::GetInstance(){ if (mInstance.get() == 0) mInstance = shared_ptr<ImpFactory>(new ImpFactory()); return mInstance; } 

The code compiles, but I get a linker error:

../../lib/oxygen/liboxygen.so.3.2.4: undefined link to "oxygen :: ImpFactory :: mInstance"

He currently has three students. Any ideas?

+7
c ++ undefined-reference static linker singleton
source share
5 answers

You should define a static instance, not just declare it. The definition creates the actual object you are referencing.

In your cpp file add the line:

 boost::shared_ptr<ImpFactory> ImpFactory::mInstance; 
+13
source share

You need a definition for your static member in the cpp file.

 boost::shared_ptr<ImpFactory> ImpFactory::mInstance; 
+2
source share

In your C ++ add this:

 boost::shared_ptr<ImpFactory> ImpFactory::mInstance; 
+2
source share

on the other side of the note, maybe you should make the instance pointer a static member of the get function, not a class, this is not too different when using the new / pointer method. but if you just create a static instance (i.e. do not use a pointer and return a link to it from the get get function), this is of great importance because:

if it is a static member of a class, its constructor is called every time (since it is global), if it is a static member of the get function, it is not built before its first call, this eases some of the problems that people face with single games, as well as the glorified global global variables, but most importantly, most linkers will omit the get function and, therefore, the entire static instance if it is never called, so you do not need to worry about calling a new one, it only uses memory, if and it is used.

0
source share

Since you are using Boost, you can consider the Singleton Boost classes. Departure:

 #include <boost/serialization/singleton.hpp> using namespace boost::serialisation; struct MyClass : public singleton<MyClass> { string name_; int age_; }; int main( int argc, char* argv[] ) { MyClass::get_mutable_instance().name_ = "Robin"; MyClass::get_mutable_instance().age_ = 21; } 

What you use depends on what you do. While I'm still a bit opposed to single player for the usual reasons, it makes sense to reuse where possible. A word of warning though: the single Boost seems to fit a bit in the libraries, so this may vary depending on which version of Boost you are using.

0
source share

All Articles