Re: singleton initialization
{ Edits: quoted clc++m banner removed. Please quote only relevant text.
-mod }
On May 15, 1:00 pm, Eric <shoo...@yahoo.com> wrote:
I created a singleton class as in the example below. The application
sporadically crashes in the second line of the main function as shown.
However, when I change the singleton such that the static pointer is a
class member (defined in the cpp file) and the instance function
creates the object if the pointer is NULL, then it works fine. I would
appreciate any explanations as to why this happens.
class CTestClass
{
public:
static CTestClass& instance()
{
static CTestClass* m_instance = new CTestClass;
return *m_instance;
}
private:
CTestClass() { /* do some stuff */ }
};
int main()
{
CTestClass::instance(); // initialize singleton here to
avoid future race conditions
// sporadically crashes here when using CTestClass::instance()
}
There is not enough real information to find out why it sporadically
crashes.
Sporadically suggests: There is a timing issue which suggests threads
are involved, and since I don't see any in main it suggests they are
created by constructors of global variables (But again not enough
information).
Moving the pointer to class static: As this seems to solve the problem
this suggests there is a memory corruption somewhere else. This
becomes hard to track down without other tools.
What does jump out. Is that the "Copy Constructor" and "Assignment
Operator" are not defined in your singelton. Thus some global object
may by making a copy of the singelton (in its constructor) and the
destruction of this copy may be interfering with the singelton
(especially if your singelton contains raw pointers).
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]