2

我正在编写一个简单的程序来理解 new 和 delete 运算符重载。参数是如何size传递给new操作符的?

作为参考,这是我的代码:

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

class loc{
    private:
        int longitude,latitude;
    public:
        loc(){
            longitude = latitude = 0;
        }
        loc(int lg,int lt){
            longitude -= lg;
            latitude -= lt;
        }
        void show(){
            cout << "longitude" << endl;
            cout << "latitude" << endl;
        }
        void* operator new(size_t size);
        void operator delete(void* p);
        void* operator new[](size_t size);
        void operator delete[](void* p);
};

void* loc :: operator new(size_t size){
    void* p;
    cout << "In overloaded new" << endl;
    p = malloc(size);
    cout << "size :" << size << endl;
    if(!p){
        bad_alloc ba;
        throw ba;
    }
    return p;
}

void loc :: operator delete(void* p){
    cout << "In delete operator" << endl;   
    free(p);
}

void* loc :: operator new[](size_t size){
    void* p;
    cout << "In overloaded new[]" << endl;
    p = malloc(size);
    cout << "size :" << size << endl;
    if(!p){
        bad_alloc ba;
        throw ba;
    }
    return p;
}

void loc :: operator delete[](void* p){
    cout << "In delete operator - array" << endl;   
    free(p);
}

int main(){
    loc *p1,*p2;
    int i;
    cout << "sizeof(loc)" << sizeof(loc) << endl;
    try{
        p1 = new loc(10,20);
    }
    catch (bad_alloc ba){
        cout << "Allocation error for p1" << endl;
        return 1;
    }
    try{
        p2 = new loc[10];
    }
    catch(bad_alloc ba){
        cout << "Allocation error for p2" << endl;
        return 1;
    }
    p1->show();
    for(i = 0;i < 10;i++){
        p2[i].show();
    }
    delete p1;
    delete[] p2;
    return 0;
}
4

1 回答 1

3

当您编写类似 的表达式new loc时,编译器具有静态类型信息,可以让它知道对象有多大loc。因此,它可以生成传递sizeof locloc::operator new. 创建数组时,编译器可以类似地确定需要多少空间来保存数组中的所有对象,方法是将数组大小乘以sizeof loc,然后还提供一些额外的空间量(以实现定义的方式确定)它将在内部使用来存储有关数组中元素数量的信息。

希望这可以帮助!

于 2013-10-21T03:33:51.740 回答