如何使用QT命名空间中使用的重载new运算符

时间:2011-11-30 07:31:45

标签: c++ qt memory-leaks operator-overloading new-operator

我正在编写一个使用QT库的C ++应用程序。我想在我的应用程序和QT中检测内存泄漏。所以,我使用这个引用http://lists.trolltech.com/qt-interest/2002-04/msg00933.html重载了main.cpp中的new和delete运算符,但是QT没有使用重载运算符。显然,它似乎是命名空间问题。如何解决这个问题。

int numAllocUnits = 0;
ofstream myLogFile("/root/memLeak.log");

class MemoryLeak_Manav
{
public:
        MemoryLeak_Manav() {
        if (!myLogFile.is_open()) {
                cout << "Unable to open file";
        }
        myLogFile << "Memory Leak Detection log File" << endl;
        printf("Memory Leak Detection On ... ");
        }

public:
        ~MemoryLeak_Manav() {
        myLogFile.close();
        if(numAllocUnits)
                printf("\nError: Memory leak detected: %d\n\n", numAllocUnits);
        else printf("\nNo memory leak detected.\n\n");
        }

public:
   void *operator new [] (size_t size);
   void *operator new (size_t size);
   void operator delete [] (void *p);
   void operator delete (void *p);
};

void * MemoryLeak_Manav::operator new(size_t size)
{
  void *newPtr;
  numAllocUnits++;
  newPtr = malloc(size);
  printf("malloc [%p allocated %d bytes]\n", newPtr, size);
  myLogFile << "malloc [" << newPtr << "allocated" << size << "bytes" << endl;
  return newPtr;
}

void  MemoryLeak_Manav::operator delete(void *p)
{
  numAllocUnits--;
  free(p);
}

void * MemoryLeak_Manav::operator new [] (size_t size)
{
  void *newPtr;
  numAllocUnits++;
  newPtr = malloc(size);
  printf("malloc [%p allocated %d bytes]\n", newPtr, size);
  myLogFile << "malloc [" << newPtr << "allocated" << size << "bytes" << endl;
  return newPtr;
}

void  MemoryLeak_Manav::operator delete [] (void *p)
{
  numAllocUnits--;
  printf("free %p\n", p);
  myLogFile << "free" << p << endl;
  free(p);
}

memLeak.log文件为空,我也没有看到任何printf的消息。

3 个答案:

答案 0 :(得分:2)

您无法在库中重载 new ,因为已经编译了库。要替换Qt中的 new ,您必须获取Qt源,将重载放在它们的任何基本文件中,然后重新编译。顺便说一句,它并不像听起来那么难。

答案 1 :(得分:0)

您使您的运算符成为一个类的成员。像这样,它们只会在类的命名空间中使用。

只需将运算符定义为全局运算符(没有类),它应该可以工作

答案 2 :(得分:0)

如果您可以在Linux上测试它,那么请查看使用Valgrind Memcheck工具。

这提供了有关泄漏和内存使用不良(双重免费,损坏,部分免费)的非常详细的信息,包括完整的堆栈跟踪。