重载delete []运算符,以允许使用析构函数缩小类型的数组

电脑

我们正在尝试重载delete []运算符,以实现面向对象数组的可收缩

它可以与没有特定析构函数的数据类型配合使用。

当数据类型具有指定的析构函数时,new []运算符需要额外的字节。

您能帮我们回答这些问题吗?

  1. 为什么new []运算符对于具有特定析构函数的数据类型需要额外的字节?
  2. 总是new []运算符会请求这些字节,还是依赖于库?
  3. 是否有可能知道数据类型是否具有带有if语句的特定析构函数

当代码试图缩小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;
}

相关回答的问题:

重载delete []运算符,带有特定参数

电脑

这可能会回答第1和第2

使用运算符new创建新数组时,通常会存储cookie以记住分配的长度(数组元素的数量),以便可以正确地释放它。

具体来说:

No cookie is required if the array element `type T` has a trivial destructor.

这意味着:

  • 由于结构A具有琐碎的析构函数,因此不需要cookie。
  • 由于结构B具有特定的析构函数,因此它需要一个sizeof(size_t)字节的cookie ,该cookie会直接存储在数组的左侧。

参考:Itanium C ++ ABI

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章