【C++】C++学习笔记之十九:关于new,delete

关于new和delete

new:先分配内存,再调用ctor -->调用malloc
delete:先调用dtor,再释放内存 -->调用free

#include <iostream>
#include <stdlib.h>
using namespace std;

class Fruit {
public:
    Fruit(int _no = 0, double _weight = 0.0, char _key = 'f'):no(_no), weight(_weight), key(_key){
        cout << "create fruit instance..." << endl;
    }
    ~Fruit(){
    cout << "destroy fruit instance..." << endl;
    }
    int no;
    double weight;
    char key;
public:
    void print(){}
    virtual void process(){}
};
class Apple : public Fruit{
public:
    Apple(int _size = 0, char _type = 'a'):size(_size), type(_type){
        cout << "create apple instance..." << endl;
    }
    ~Apple(){
    cout << "destroy apple instance..." << endl;
    }
    int size;
    char type;
public:
    void save(){}
    virtual void process(){}
};
inline void* operator new(size_t size){
    cout << "global new function" << endl;
    return malloc(size);
}
inline void operator delete(void *ptr){
    cout << "global delete function" << endl;
    return free(ptr);
}
int main(int argc, char ** argv){

    cout << "[Test 1] : normal Fruit instance:" << endl;
    {
        Fruit f;
    }
    cout << "[Test 2] : normal Apple instance:" << endl;
    {
        Apple apl;
    }
    cout << "[Test 3] : global new and delete Fruit instance pointer: " << endl;
    {
        Fruit *pf = new Fruit();
        delete pf;
        pf = NULL;
    }
    cout << "[Test 4] : global new and delete Apple instance pointer:" << endl;
    {
        Apple *pa = new Apple();
        delete pa;
        pa = NULL;
    }
    return 0;
}

执行结果:

Paste_Image.png

重载operator new,operator delete,operator new[] 和 operator delete[]

全局重载:
作为成员函数重载:(常用作内存池的设计)

注:当new,delete, new[] 和delete[]使用全局重载的时候,其范围是整个程序范围内的,其影响深远,应谨慎使用。

重载operator new() 和 operator delete()

basic_string 使用new(extra)扩充申请量

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容