c++ - 重载 operator new - 误导性输出

标签 c++ operator-overloading new-operator operator-keyword

我试图了解放置新/删除的工作原理,因此我编写了以下程序:

# include <iostream>
# include <cstdlib>
using namespace std;

class Test {};
void * operator new (size_t size) throw (std::bad_alloc){
    cout<<"Calling New:"<<endl;
    return new (malloc(size)) Test() ;
}

void operator delete (void *ptr) throw () {
    cout<<"Calling Delete:"<<endl;
    free (ptr) ;
}

int main ()
{
    cout<<"Hello"<<endl;
    Test *ptr = new Test () ;
    delete ptr ;
    return 0;
}

对于上面的代码,我得到以下输出:

Calling New:
Calling New:
Calling New:
Calling New:
Calling New:
Calling New:
Calling Delete:
Calling New:
Calling New:
Calling New:
Calling New:
Calling New:
Calling New:
Calling Delete:
Hello
Calling New:
Calling Delete:

在输出中,可以看到 operator new 被调用了多次(即使只创建了一个 Test 实例)并且 delete 被调用的次数较少。

有人可以建议这里有什么问题吗?

谢谢

最佳答案

可能发生的情况是 C++ 库使用 operator new 为其内部用途分配内存。例如,写入 std::cout 很可能会触发一些内部缓冲区的分配,从而导致调用重载的 operator new

关于c++ - 重载 operator new - 误导性输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17455918/

相关文章:

c++ - 奇怪的无序 map 情况

c++ - 为什么 == 重载可以访问参数的私有(private)成员

javascript - 我们可以在使用 "new"运算符创建对象时省略括号吗?

c++ - 通过在另一组上调用 erase(iterator) 从一组中删除元素。这是正常行为吗?

c++ - 从 C++ 中的函数返回引用的推荐方法

c++ - 在 Cloud9 上安装 AWS C++ SDK 时出现问题

c++ - 从 std::ostream 重载 << 运算符时,为什么编译器会给出 "too many parameters for this operator function"错误?

c++ - 如何用指针类重载比较运算符

c++ - 使用变量定义数组大小和使用新运算符 c++ 有什么区别?

java - SimpleXML 枚举区分大小写