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

关于new和delete

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

#include 
#include 
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)扩充申请量

你可能感兴趣的:(【C++】C++学习笔记之十九:关于new,delete)