gpt4 book ai didi

c++ - Loki::Singleton、Loki::SmartPtr 和std::vector 奇怪的内存问题

转载 作者:行者123 更新时间:2023-11-28 04:00:18 24 4
gpt4 key购买 nike

我在 VC express 2008 下使用 Loki::SingletonLoki::SmartPtrstd::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?

提前致谢。

最佳答案

当您使用 VC 时,您应该能够在 Debug模式下运行您的代码,按 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() 函数...

但我可能错了,你必须检查一下。

关于c++ - Loki::Singleton、Loki::SmartPtr 和std::vector 奇怪的内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1094276/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com