C++重载内存分配时需要注意的地方

先上测试代码:

#include <stdio.h>
#include <malloc.h>
#include <new>

//#define VF
//#define FLAG

class MemObj
{
public:
#ifdef VF
  virtual MemObj(void) {}
#endif // VF
  
  static void* operator new(size_t stSize)
  {
    printf("operator new(size_t) %d\n", stSize);
    return malloc(stSize);
  }

#ifdef FLAG
  static void operator delete(void* pMemory)
  {
    printf("operator delete(void*)\n");
    free(pMemory);
  }
#endif

  static void operator delete(void* pMemory, size_t stSize)
  {
    printf("operator delete(void*, size_t) %d\n", stSize);
    free(pMemory);
  }
};

class Test : public MemObj
{
private:
  int m_nValue;
};

int main(int argc, char** argv)
{
  MemObj* pObj = new MemObj();
  delete pObj;

  Test* pTest = new Test();
  delete pTest;

  pObj = new Test();
  delete pObj;


  return 0;
}



测试1:

测试条件:

不定义宏VF和FLAG

测试结果:

operator new(size_t) 1
operator delete(void*, size_t) 1
operator new(size_t) 4
operator delete(void*, size_t) 1
operator new(size_t) 4
operator delete(void*, size_t) 1



测试2:

测试条件:

定义宏FLAG但不定义宏VF

测试结果:

operator new(size_t) 1
operator delete(void*)
operator new(size_t) 4
operator delete(void*)
operator new(size_t) 4
operator delete(void*)



测试3:

测试条件:

定义宏VF但不定义宏FLAG

测试结果:

operator new(size_t) 4
operator delete(void*, size_t) 4
operator new(size_t) 8
operator delete(void*, size_t) 8
operator new(size_t) 8
operator delete(void*, size_t) 8



测试4:

测试条件:

同时定义宏VF和FLAG

测试结果:

operator new(size_t) 4
operator delete(void*)
operator new(size_t) 8
operator delete(void*)
operator new(size_t) 8
operator delete(void*)


分析1:

对比测试1和测试2我们可以看出:重载了operator new(size_t stSize)后,在删除的时候,如果没有定义了void operator delete(void* pMemory)了,那么会调用void operator delete(void* pMemory, size_t stSize),而如果定义了void operator delete(void* pMemory),不管是否定义void operator delete(void* pMemory, size_t stSize)都会调用void operator delete(void* pMemory)。

结论1:

重载operator new(size_t)后,如果同时重载了operator delete(void*),删除时候会调用operator delete(void*)否则会调用operator delete(void*, size_t)


分析2:

对比测试1和测试3我们可以看出:不将基类的西沟函数定义为虚析构函数,会有内存泄漏

你可能感兴趣的:(C++重载内存分配时需要注意的地方)