c++中的new的问题
怪我咯
怪我咯 2017-04-17 14:31:05
[C++讨论组]
怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(1)
高洛峰
#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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号