如何在不使用删除运算符的情况下删除由新创建的内存 [英] How Can I Delete Memory Created By New Without Using Delete Operator
本文介绍了如何在不使用删除运算符的情况下删除由新创建的内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
int * ptr;
ptr = new int a [20];
删除在不使用delete的情况下创建为20个整数的内存
int *ptr;
ptr=new int a[20];
delete memory created to 20 integers without using delete
推荐答案
语言C ++有一些规则,例如分配new的内存必须在释放时释放。
您可以:
1.覆盖命令new并使用您自己的实现删除
2.使用其他方法像malloc和free一样的内存管理。
3.在范围内分配内存。
4.使用一些auto_ptr。 (高级技术)
但永远不要骄傲:成为一个好公民,如果你想开发软件,你应该遵守规则。
the language C++ has some rules, for instance that memory which is allocated the new has to be freed with release.
You can:
1. overwrite the command new and delete with your own implementation
2. use other methods for memory managment like malloc and free.
3. allocate memory in scopes.
4. use some auto_ptr. (advanced technology)
But never ever ferget: be a good citizen and if you want to develop software you should stick to the rules.
你可以使用多种方法如果没有在程序中直接编写删除操作符,请执行此操作:
You could use a number of ways to to do it without literally writing the delete operator in your program:
#include <memory>
int main()
{
int *ptr=new int[20];
std::allocator<int>().deallocate(ptr, 20);
}
#include <memory>
int main()
{
int *ptr=new int[20];
std::default_delete<int[]>()(ptr);
}
#include <memory>
int main()
{
int *ptr=new int[20];
std::unique_ptr<int[]> p(ptr);
}
#include <boost/smart_ptr.hpp>
int main()
{
int *ptr=new int[20];
boost::scoped_array<int> p(ptr);
}
等
所有这些都在某处在内部执行delete [],并将ptr的副本作为参数,这是实际释放该内存的参数。
etc.
All of these somewhere internally execute delete[] with a copy of your ptr as the argument which is what actually deallocates that memory.
这篇关于如何在不使用删除运算符的情况下删除由新创建的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文