gpt4 book ai didi

c++ - memset 在模板类构造函数中泄漏内存

转载 作者:行者123 更新时间:2023-11-28 08:00:22 27 4
gpt4 key购买 nike

这个类构造器正在泄漏内存,我不能说这是怎么回事。我怎么知道?如果我注释掉第二个 ctor 行,泄漏就会消失。

template< class T, int fixedSize >
class Resource_Cache{

private:

ID3D11Device * m_pDeviceRef; // the one that actually can create stuff

UINT m_iCurrentIndex; // next slot to be allocated, also the ID of the resources
//UINT m_nFreedSlots; // how many freed slot there are?

T* m_cache[fixedSize]; // the container per se

struct SlotInfo{

UINT nUseCount;
Resource_Descriptor<T> desc;

} m_slotsInfo[fixedSize];//use a hashtable<desc,index on m_cache>;


Resource_Cache(); //denied default ctor

public:

Resource_Cache( ID3D11Device * pDevice_p ): m_pDeviceRef(pDevice_p), m_iCurrentIndex(0){

memset(m_cache, NULL, fixedSize*sizeof(T*));
memset( m_slotsInfo, 0, fixedSize*sizeof(SlotInfo)); // zero slotsInfo memory(CAUSING LEAKS)
}
...

可能很简单,但我一无所知..

  • 编辑回答 -正如 PermanentGuest 所说:不。它不会给基本类型带来问题。但是,如果您的 Resource_Descriptor 类型 T 有一些通过 memset 在构造函数(例如字符串)中分配内存的实现,您将将该类的任何内部指针重置为 NULL,从而拒绝其析构函数删除内存的机会。 – 永久访客

std::string 是问题所在,已解决。

最佳答案

代替

Resource_Cache( ID3D11Device * pDevice_p ): m_pDeviceRef(pDevice_p), m_iCurrentIndex(0){

memset(m_cache, NULL, fixedSize*sizeof(T*));
memset( m_slotsInfo, 0, fixedSize*sizeof(SlotInfo)); // zero slotsInfo memory(CAUSING LEAKS)
}

Resource_Cache( ID3D11Device * pDevice_p )
: m_pDeviceRef( pDevice_p )
, m_iCurrentIndex()
, m_cache()
, m_slotsInfo()
{}

我很确定这不会解决您断定是由于内存泄漏或内存泄漏(如果有的话)引起的症状,但至少它消除了您可能的原因我们专注于,通过在(安全的)C++ 中而不是(不安全的)C 中进行归零。

哦,好吧,因为未指定的完全未描述 Resource_Descriptor<T>它实际上可能会解决问题。但你不会使用 memset如果那不是 POD,现在你会吗?或者,也许你会?

关于c++ - memset 在模板类构造函数中泄漏内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11632348/

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