使用delete运算符删除void指针 [英] deleting a void pointer using delete operator

查看:992
本文介绍了使用delete运算符删除void指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码出了什么问题。它应该是什么。因为它抛出一个错误。操作符'delete',应用于void *参数。

  int i; 
void * ptr =& i;

delete ptr;


解决方案



int i;

b

第二行尝试将整数转换为指针。在特殊情况下,你可以强迫过去的编译器与 reinterpret_cast ;但是如果整数包含一个有效的指针值,程序只会正常工作。 ( UPDATE :现在已经编辑问题,改为使用 i 的地址;因此此行不再错误。)



第三行尝试使用无效的指针类型删除无效的内存。


be。


其他。不知道你想做什么,这是不可能说的。也许你想要:

  int i; 
void * ptr =& i; //指向`i`,丢失类型信息。




运算符 delete ,应用于 void * 参数。


您必须只有 delete 您先前分配的对象 new ;并且指针必须是正确的类型。



(或者基类,如果它是一个带有虚拟析构函数的类类型) / p>

所以下面是正确的;但无意义,除非你有一个很好的动态分配理由:

  int * ptr = new int; 
delete ptr;

当然,如果你编写的代码应该对内存泄漏和运行时错误具有鲁棒性,您应该使用 RAII 类型(如容器和智能指针)管理所有动态内存。所以,如果你需要一个动态对象,你应该做:

  std :: unique_ptr< int& ptr(new int); 

如果要在当前作用域结束时删除它或将其移动到另一个作用域,或

  auto ptr = std :: make_shared< int>();如果您想在多个作用域之间共享所有权,则

。在这两种情况下,指针将在您完成后自动删除对象。


whats wrong with the code. What it should be. As it is throwing an error. Operator 'delete', applied to void* argument.

int i;
void *ptr = &i;

delete ptr;

解决方案

whats wrong with the code.

Everything except int i;

The second line attempts to convert an integer to a pointer. In special circumstances, you could force that past the compiler with reinterpret_cast; but the program would only behave correctly if the integer somehow contained a valid pointer value. (UPDATE: the question has now been edited to take the address of i instead; so this line is no longer wrong).

The third line attempts to delete invalid memory using an invalid pointer type.

What it should be.

Something else. Without knowing what you want to do, it's impossible to say. Perhaps you want:

int i;
void * ptr = &i;  // Points to `i`, losing type information.

Operator delete, applied to void* argument.

That's always wrong. You must only delete an object you previously allocated with new; and the pointer must be to the correct type.

(or to a base class, if it's a class type with a virtual destructor)

So the following would be correct; but pointless unless you have a good reason for dynamic allocation:

int * ptr = new int;
delete ptr;

And of course, if you're writing code that should be robust against memory leaks and runtime errors, you should manage all dynamic memory using RAII types such as containers and smart pointers. So, if you need to a dynamic object, you should do:

std::unique_ptr<int> ptr(new int);

if you want a to delete it at the end of the current scope or move it into another scope; or

auto ptr = std::make_shared<int>();

if you want to share ownership between more than one scope. In either case, the pointers will delete the object automatically once you've finished with it.

这篇关于使用delete运算符删除void指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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