【问题标题】:new and delete operator overloadingnew 和 delete 运算符重载
【发布时间】:2013-10-21 03:30:41
【问题描述】:

我正在编写一个简单的程序来理解 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;
}

【问题讨论】:

标签: c++ operator-overloading new-operator


【解决方案1】:

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

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-04
    • 2014-03-26
    • 2013-03-12
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    相关资源
    最近更新 更多