简体   繁体   English

新和删除运算符重载

[英]new and delete operator overloading

I am writing a simple program to understand the new and delete operator overloading. 我正在编写一个简单的程序,以了解new和delete运算符的重载。 How is the size parameter passed into the new operator? 如何将size参数传递给new运算符?

For reference, here is my code: 供参考,这是我的代码:

#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;
}

When you write an expression like new loc , the compiler has static type information that lets it know how large a loc object is. 当您编写类似new loc的表达式时,编译器具有静态类型信息,可让其知道loc对象的大小。 Therefore, it can generate code that passes sizeof loc into loc::operator new . 因此,它可以生成将sizeof loc传递给loc::operator new When creating an array, the compiler can similar determine how much space is needed to hold all the objects in the array by multiplying the array size by sizeof loc , and then also providing some additional amount of space (determined in an implementation-defined way) that it will use internally to store information about the number of elements in the array. 创建数组时,编译器可以通过将数组sizeof locsizeof loc ,然后还提供一些额外的空间(以实现定义的方式确定),类似地确定需要多少空间来容纳数组中的所有对象。它将在内部用于存储有关数组中元素数量的信息。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM