加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 在void指针上使用delete []运算符释放内存

发布时间:2020-12-16 10:25:49 所属栏目:百科 来源:网络整理
导读:参见英文答案 Is it safe to delete a void pointer?????????????????????????????????????13个 我们可以通过在void *上使用delete []运算符来释放原始数据类型的数组. 防爆. char* charPtr = new char[100]void* voidPtr = (void*)charPtr;delete[] voidPtr
参见英文答案 > Is it safe to delete a void pointer?????????????????????????????????????13个
我们可以通过在void *上使用delete []运算符来释放原始数据类型的数组.
防爆.

char* charPtr = new char[100]
void* voidPtr = (void*)charPtr;
delete[] voidPtr;

或者可以使用delete运算符释放它

delete voidPtr

我不指望它会调用析构函数.我只期望它释放新运算符分配的内存.

解决方法

不,这是无效的,如果我们看一下 C++ draft standard就是 undefined behavior 5.3.5删除说(强调我的未来):

The operand shall be of pointer to object type or of class type. If of class type,the operand is contextually implicitly converted (Clause 4) to a pointer to object type. The delete-expression’s result has type void.78

和脚注78说:

This implies that an object cannot be deleted using a pointer of type void* because void is not an object type.

另一方面,free允许您使用void *但分配必须通过malloc,calloc或realloc.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读