Memset 泄漏 MEM 在模板类构造函数中

memset leaking mem at template class constructor

本文关键字:构造函数 泄漏 MEM Memset      更新时间:2023-10-16

这个类 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)
    }
 ...

可能是简单的东西,但我一无所知。

  • 编辑回答 -正如永久客人所说:不。它不会给基本类型带来问题。但是,如果你的 T Resource_Descriptor类型有一些实现,它通过 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>它实际上可能会解决问题。但是,如果那不是 POD,您就不会使用 memset,现在你会吗?或者,也许你会?