ostream运算符不应该调用重载的新运算符?

时间:2016-11-10 15:20:14

标签: c++ operator-overloading operators new-operator

我正在阅读C ++中的思考(第1卷 - 第597页)。我刚刚遇到了一个重载全局new / delete操作符的概念。

#include <cstdio>
#include <cstdlib>
using namespace std;
void* operator new(size_t sz) {
    printf("operator new: %d Bytes\n", sz);
    void* m = malloc(sz);
    if(!m) puts("out of memory");
    return m;
}
void operator delete(void* m) {
    puts("operator delete");
    free(m);
}
class S {
    int i[100];
    public:
        S() { puts("S::S()"); }
       ~S() { puts("S::~S()"); }
};
int main() {
    puts("creating & destroying an int");
    int* p = new int(47);
    delete p;
    puts("creating & destroying an s");
    S* s = new S;
    delete s;
    puts("creating & destroying S[3]");
    S* sa = new S[3];
    delete []sa;
}

以此为例说明如下: -

  

请注意,使用printf()和puts()而不是iostream。这个   是因为当创建一个iostream对象时(就像全局cin一样,   cout和cerr),它调用new来分配内存。用printf(),你   不要陷入死锁,因为它不会调用new来初始化   本身。

现在检查上面语句的正确性,我包含了iostream库,并且还在说conttructor中添加了cout语句,希望得到一个无限循环,因为我期待cout会调用new并且它将是无限循环。但它运作正常。没有ambiquity或无限循环。

我在这里错过了什么吗?

0 个答案:

没有答案
相关问题