在VC express 2008下使用 Loki :: Singleton , Loki :: SmartPtr 和 std :: vector 时遇到问题以下是我的来源。
#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 ;
}
编译和链接没有问题,但程序完成后会弹出错误:
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.
似乎某些内存被删除了两次,我不太确定。这是VC的错误还是我想念Loki?
提前致谢。
答案 0 :(得分:1)
当您使用VC时,您应该能够以调试模式运行代码,逐步执行stp(F10,F11)以查看它的中断位置。
无论如何,看看Loki singleton code,似乎错误来自SingletonHolder :: DestroySingleton()中的断言:
SingletonHolder<T, CreationPolicy, L, M, X>::DestroySingleton()
00837 {
00838 assert(!destroyed_); // there, but it's a wild guess
00839 CreationPolicy<T>::Destroy(pInstance_);
00840 pInstance_ = 0;
00841 destroyed_ = true;
00842 }
该函数似乎由LifetimePolicy(此处为DefaultLifetime)调用,如此代码所示:
00800 template
00801 <
00802 class T,
00803 template <class> class CreationPolicy,
00804 template <class> class LifetimePolicy,
00805 template <class, class> class ThreadingModel,
00806 class MutexPolicy
00807 >
00808 void SingletonHolder<T, CreationPolicy,
00809 LifetimePolicy, ThreadingModel, MutexPolicy>::MakeInstance()
00810 {
00811 typename ThreadingModel<SingletonHolder,MutexPolicy>::Lock guard;
00812 (void)guard;
00813
00814 if (!pInstance_)
00815 {
00816 if (destroyed_)
00817 {
00818 destroyed_ = false;
00819 LifetimePolicy<T>::OnDeadReference();
00820 }
00821 pInstance_ = CreationPolicy<T>::Create();
00822 LifetimePolicy<T>::ScheduleDestruction(pInstance_, // here
00823 &DestroySingleton);
00824 }
00825 }
我不确定为什么它会被调用两次,但我想单弹头的指针首先在SingletonHolder实例销毁时被销毁(指针,而不是实例),然后LifetimePolicy尝试调用它的DestroySingleton()函数...
但我可能错了,你必须检查一下。
答案 1 :(得分:1)
IMR,你不能在stl容器中使用某些智能指针,这就是发生的确切问题。如果内存服务,它与stl容器如何复制不符合智能指针期望使用的值的方式有关。