> Now to my problem this piece of code doesn't compile I get the following
error I can't understand what it is.
start.obj : error LNK2001: unresolved external symbol "private: __thiscall
Outdoors::Outdoors(void)" (??0Outdoors@@AAE@XZ)
Debug/slask.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.
You have declared the default constructor for Outdoors (as private), and you
are using it (when creating the instance), but you have not defined it.
Define it (at least as empty, unless you have any logic to put in it), and
the error will disappear.
BTW there are other errors:
1) You have *defined* Outdoors::onlyInstance in the header. This would mean
that if the header is included in two modules, there will be multiple
definition of the same object, which is forbidden (and will most probably
cause the linker to complain). Please create a new module (e.g.
outdoors.cpp) and define Outdoors::onlyInstance there.
2) Your code never destroys the singleton. That may be what is desired, but
be aware of that fact. You will have at least a memory leak for the
singleton object, if not other leaks. As an example, if the singleton keeps
a file open and writes to it, and if it closes the file in its destructor,
the file may be closed by the OS instead of your application, which means
that some data may be buffered and not written at the end, i.e. the file may
get corrupted. One can easily think of more examples whenever the Outdoors
destructor is nontrivial.
3) It is too easy to delete the singleton (e.g. delete
Outdoors::instance()).
To solve problems 2 and 3, usually the following pattern is used:
// outdoors.h
class Outdoors
{
public:
static Outdoors &Outdoors::instance();
// etc.
private:
Outdoors() { /* ... */ } // note that this is a definition as well
// etc.
};
// outdoors.cpp
Outdoors &Outdoors::instance()
{
static Outdoors onlyInstance;
return onlyInstance;
}
Note that instance() returns a reference instead of pointer, so it would be
harder to delete it inadvertently. C++ Standard guarantees that Outdoors
constructor will be called first time the instance() method is called, and
destructor will be called upon returning from main(). However, there is also
a couple of pitfalls with this approach: (1) it is unspecified when exactly
after main() the singleton will be destroyed; particularly this is important
if you have multiple singletons depending on each other, (2) possible
threading issues which are OT here.
Rade