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

标签 c++ templates constructor memory-leaks memset

这个类构造器正在泄漏内存,我不能说这是怎么回事。 我怎么知道?如果我注释掉第二个 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/

相关文章:

C++:如何获取 vector 来打印用户输入?

C++:与 OpenCV 互相关

java - 是否有任何框架可以将一个节点生成的数据与不可靠网络中的所有其他节点同步?

templates - 模板比较在模板体内发生变化

c++ - 将 "stored"可变参数模板类型解压到模板参数中

java - 使用类构造函数设置数组值时出现 NullPointerException

javascript - OO编程: Should I use functions or object literals

c++ - boost 线程中的错误 "expression cannot be used as a function"?

c++ - 抽象类和唯一指针

C++:多态类模板