我们正在尝试重载delete []运算符,以实现面向对象数组的可收缩。
它可以与没有特定析构函数的数据类型配合使用。
当数据类型具有指定的析构函数时,new []运算符需要额外的字节。
您能帮我们回答这些问题吗?
当代码试图缩小B的数组时,该代码应引发未处理的异常。
#include<cstdlib>
#include<iostream>
using namespace std;
void*operator new[](size_t s){
cout<<"Block size: "<<s<<endl;
return malloc(s);
}
void operator delete[](void*p){
free(p);
}
void operator delete[](void*p,size_t s){
//Is it possible to know if the data type has a specific destructor?
bool destructor=0;
if(destructor){
p=(char*)p-8,s+=8;
}
cout<<"New block size: "<<s<<endl;
if(realloc(p,s)!=p)throw 0;
}
struct A{
char a;
A():a(0){}
~A()=default;
};
struct B{
char b;
B():b(0){}
~B(){}
};
int main(){
unsigned S=10,s=4;
cout<<"Creating "<<S<<" A's"<<endl;
A*a=new A[S];
cout<<"Creating "<<S<<" B's"<<endl;
B*b=new B[S];
cout<<"Shrinking A to "<<s<<" elements"<<endl;
operator delete[](a,sizeof(A)*s);
cout<<"Shrinking B to "<<s<<" elements"<<endl;
operator delete[](b,sizeof(B)*s);
cout<<"Deleting A and B"<<endl;
delete[]b,delete[]a;
return 0;
}
相关回答的问题:
这可能会回答第1点和第2点
使用运算符
new
创建新数组时,通常会存储cookie以记住分配的长度(数组元素的数量),以便可以正确地释放它。具体来说:
No cookie is required if the array element `type T` has a trivial destructor.
这意味着:
sizeof(size_t)
字节的cookie ,该cookie会直接存储在数组的左侧。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句