指针数组的重载删除[]

overload delete[] for array of pointers(指针数组的重载删除[])

本文介绍了指针数组的重载删除[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为代码搜索重载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

这篇关于指针数组的重载删除[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:指针数组的重载删除[]

基础教程推荐