I had encountered a problem while using Loki::Singleton, Loki::SmartPtr, and std::vector under VC express 2008. Following is my source.
#include <iostream>
#include <vector>
#include <loki/Singleton.h>
#include <loki/SmartPtr.h>
class Foo {
public:
std::vector<Loki::SmartPtr<Foo>> children ;
void add() {
Loki::SmartPtr<Foo> f = new Foo ;
children.push_back(f) ;
}
Foo () {
}
~Foo () {
}
} ;
typedef Loki::SingletonHolder<Foo> SingletonFoo ;
int main ()
{
std::cout << "Start" << std::endl ;
SingletonFoo::Instance().add() ;
std::cout << "End" << std::endl ;
}
Compiling and linking has no problem, but after the program finished, an error pops:
Windows has triggered a breakpoint in test.exe.
This may be due to a corruption of the heap, which indicates a bug in test.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while test.exe has focus.
The output window may have more diagnostic information.
It seems some memory are deleted twice, I am quite not sure. Is that a bug of VC or I miss used Loki?
Thanks in advance.
As you’re using VC, you should be able to run your code in debug mode, step by stp (F10,F11) to see where it breaks.
Anyway, looking at the Loki singleton code, it seems that the error comes from the assert in SingletonHolder::DestroySingleton() :
That function seems to be called by the LifetimePolicy (here DefaultLifetime) as this code suggests :
I’m not sure why it is called twice, but I guess the pointer to the singleton is first destroyed (the pointer, not the instance) on the SingletonHolder instance destruction and then the LifetimePolicy try to call it’s DestroySingleton() function…
But I might be wrong, you’ll have to check that.