简体   繁体   中英

overload delete[] for array of pointers

I search a method to overload operator of delete[] or suitable destructor for a code:

#include <iostream>
#include <string>
using namespace std;

class A {
private:
    string name;
public:
    A(string name){
        this->name=name;
    };
    ~A(){
        cout<<"Destructor. Destroyed "<<name<<"\n";
    };
    void operator delete(void* p, A* a){
        cout<<"-Delete "<<a->name<<"\n";
    };
    void operator delete(void* pointer){
        cout<<"Delete"<<"\n";
    };
    void operator delete[](void* pointer){
        cout<<"Delete[]"<<"\n";
    };
};

int main(){
int number = 5;
A** a = new A* [ number ];

delete [] a;
    system("pause");
    return 0;
};

But whatever I tried default delete[] is started each time from the file delete2.cpp. What do I do wrong? [ADDED] Added an attempt to overload delete[].

Your code is not creating or destroy instances of A, only pointers to it.

#include <iostream>
#include <string>
using namespace std;

class A {
private:
    string name;
public:
    A() {}
    A(string name){
        this->name=name;
    };
    ~A(){
        cout<<"Destructor. Destroyed "<<name<<"\n";
    };
    void operator delete(void* p, A* a){
        cout<<"-Delete "<<a->name<<"\n";
    };
    void operator delete(void* pointer){
        cout<<"Delete"<<"\n";
    };
    void operator delete[](void* pointer){
        cout<<"Delete[]"<<"\n";
    };
};

int main(){
int number = 5;
A* a = new A[ number ];

delete [] a;
    system("pause");
    return 0;
};

Calls operator[] as expected: http://ideone.com/EuS3Hi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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