c++中的new的问题

查看:85
本文介绍了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

这篇关于c++中的new的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆