删除void指针保证删除正确的大小? [英] Does deleting void pointer guarantee to delete right size?

查看:155
本文介绍了删除void指针保证删除正确的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

是否可以安全地删除void指针?


说我有一个分配给一个类 MyClass ,分配如下: / p>

  MyClass * myClassPtr = new MyClass 

我存储对 void * 其中我只是说

  myListOfPointers.add(static_cast< void *>(myClassPtr)); //这必须是void * 

后来我释放内存,而不是这样做:

  delete myClassPtr 

我使用:

  delete MyListOfPointer.get(0)
void * p $ p>

(说myClassPtr引用在零索引。因为这个列表可以存储不同类型的指针,所以我不知道我删除的指针的类型:



所以我不能做任何事情

  delete static_cast< MyClass *>(MyListOfPointer.get(0))

这样会释放正确的内存大小吗? ( sizeof(MyClass))?



注意:

我没有找到任何指向智能指针的回答。

解决方案

删除 void * 会导致未定义的行为, >


5.3.5删除[expr.delete]



1 delete-expression运算符销毁最新派生的对象(1.8)或由新表达式创建的数组。

[...]

操作数应具有指向对象类型的指针,具有单个非显式转换函数(12.3.2)的类类型到指向对象类型的指针。结果有void类型。 78



78)这意味着不能使用类型为void *的指针删除对象,因为void不是对象类型。


强调我。






所以即使你说不说,答案是创建某种形式的智能指针。它需要使用类型擦除来从外部隐藏类型(允许异构列表),但内部跟踪它给出的类型以及如何删除它。有点像 boost :: any


Possible Duplicate:
Is it safe to delete a void pointer?

Say I have a new allocation to a class called MyClass and allocation is as simple as:

MyClass *myClassPtr = new MyClass();

And I store reference to the list of void* where I simply say

myListOfPointers.add(static_cast<void*>(myClassPtr)); // this has to be void*

And later I release memory so instead of doing:

delete myClassPtr

I use:

delete MyListOfPointer.get(0)

(Say myClassPtr reference is at zero-index.) Also, please note that it has to be void* since this list can store different types of pointers so I wouldn't know the type of pointer that I am deleting:

So I can't do any thing like:

delete static_cast<MyClass*>(MyListOfPointer.get(0))

Is this way going to release the correct memory size? (sizeof(MyClass))?

Note:
I am not looking for any answer pointing to smart pointers.

解决方案

Deleting through a void* results in undefined behavior, so you are guaranteed nothing.

5.3.5 Delete [expr.delete]

1 The delete-expression operator destroys a most derived object (1.8) or array created by a new-expression.
[...]
The operand shall have a pointer to object type, or a class type having a single non-explicit conversion function (12.3.2) to a pointer to object type. The 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.

Emphasis mine.


So even though you said not to say it, the answer is to create some form of smart pointer. It would need to use type-erasure to hide the type externally (allowing the heterogeneous list), but internally keep track of the type it was given and how to delete it. Something much like boost::any.

这篇关于删除void指针保证删除正确的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆