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

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

我正在编写一个使用 QT 库的 C++ 应用程序。我想检测我的应用程序和 QT 中的内存泄漏。因此,我使用此引用在我的 main.cpp 中重载了 new 和 delete 运算符 http://lists.trolltech.com/qt-interest/2002-04/msg00933.html , 但 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 的消息。

最佳答案

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

关于c++ - 如何使用 QT 命名空间中使用的重载 new 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8322519/

相关文章:

c++ - 如何在 C++ 中实现临时?

c++ - 在不使用新数组的情况下就地旋转二维数组 - 最佳 C++ 解决方案?

c++ - 如何在 QtCreator 上使用 FTD2xx 库(使用 MSVC2012 编译器)

c++ - Qt 控制台应用程序 "WARNING: QApplication was not created in the main() thread"

AngularJS - $destroy 是否删除事件监听器?

c++ - 重载前缀/后缀编译器优化

c++ - 在父部件中居中子部件(布局中添加了父部件)

c++ - 退出时多线程Qt应用程序不会停止

c# - 编译的表达式树会泄漏吗?

javascript - 在waveurfer.js加载中更改音频URL会导致AngularJS应用程序中的内存泄漏