为指针数组重载 delete[]
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<<"\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;
};
但无论我尝试什么,默认删除[] 每次都会从文件 delete2.cpp 启动。我做错了什么?
[已添加] 添加了重载 delete[] 的尝试。
您的代码没有创建或销毁 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<<"\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;
};
按预期调用运算符[]:http://ideone.com/EuS3Hi
我搜索了一种方法来重载 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<<"\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;
};
但无论我尝试什么,默认删除[] 每次都会从文件 delete2.cpp 启动。我做错了什么? [已添加] 添加了重载 delete[] 的尝试。
您的代码没有创建或销毁 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<<"\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;
};
按预期调用运算符[]:http://ideone.com/EuS3Hi