首页 > c++中的new的问题

c++中的new的问题

在一篇博客上看到,下面的这段代码:

#include <iostream>

using namespace std;

class C {
public:
    C(int i) : i(i) {
        cout << "C constructor." << endl;
    }

    ~C() {
        cout << "C destructor." << endl;
    }

    // 此处声明为static或non-static均可,下同
    /* static */ void *operator new(size_t size, void *p, const string& str) {
        cout << "In our own operator new." << endl;
        cout << str << endl;
        if (!p) {
            cout << "Hey man, are you aware what you are doing?" << endl;
            return ::operator new(size);
        }
        return p;
    }

    /* static */ void operator delete(void *p) {
        cout << "We should do nothing in operator delete." << endl;
        // 如果取消下一行的注释,程序会在执行时crash
        // ::operator delete(p);
    }

    void f() {
        cout << "hello object, i: " << i << endl;
    }

private:
    int i;
};

int main() {
    char buf[sizeof(C)];
    C *pc = new (buf, "Yeah, I'm crazy!") C(1024);
    pc->f();
    delete pc;
    return 0;
}

有点困惑:
1.其中类里面的operator new()函数里面,调用了一个全局的::operator new(),这个调用的operator new(size)placement new还是default new
2.在main()函数中, C *pc = new (buf, "Yeah, I'm crazy!") C(1024);,这一句后面的C(1024)是调用的C的构造函数,还是说有1024个C?还有为什么这里的new里面的参数只有两个?


#include <iostream>

using namespace std;

class C {
public:
    C(int i) : i(i) {
        cout << "C constructor." << endl;
    }

    ~C() {
        cout << "C destructor." << endl;
    }

    // 此处声明为static或non-static均可,下同
    /* static */ void *operator new(size_t size, void *p, const string& str) {
        cout << "In our own operator new." << endl;
        cout << str << endl;
        if (!p) {
            cout << "Hey man, are you aware what you are doing?" << endl;
            return ::operator new(size); // !! 这是调用的全局的operator new(size_type)
        }
        return p;
    }

    /* static */ void operator delete(void *p) {
        cout << "We should do nothing in operator delete." << endl;
        // 如果取消下一行的注释,程序会在执行时crash
        // ::operator delete(p); // !! 这里当然不能直接释放,你的内存可能是从operator new 参数中的buf分配来的,是栈上的内存 
    }

    void f() {
        cout << "hello object, i: " << i << endl;
    }

private:
    int i;
};

int main() {
    char buf[sizeof(C)];
    C *pc = new (buf, "Yeah, I'm crazy!") C(1024); // !! 当然是构造函数,再怎么也不能是数组,因为不是[]
                                                   // placement new 靠C(1024)构造函数来确定第一个参数的值
    pc->f();
    delete pc;
    return 0;
}

参考:wikipedia-new

【热门文章】
【热门文章】