指针数组的重载删除[]

我为代码搜索重载Delete[]的运算符或合适的析构函数的方法:

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

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

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

delete [] a;
    system("pause");
    return 0;
};
但是,无论我尝试什么,每次都会从文件delete2.cpp启动默认的删除[]。我做错了什么? [已添加]添加了重载删除[]的尝试。


解决方案

您的代码不是创建或销毁A的实例,而是指向它的指针。

#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<<"
";
    };
    void operator delete(void* p, A* a){
        cout<<"-Delete "<<a->name<<"
";
    };
    void operator delete(void* pointer){
        cout<<"Delete"<<"
";
    };
    void operator delete[](void* pointer){
        cout<<"Delete[]"<<"
";
    };
};

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

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

如期调用运算符[]:http://ideone.com/EuS3Hi

相关文章