在外部函数中分配的数组内存的耐久性 [英] Endurance of array memory allocated in external function

查看:62
本文介绍了在外部函数中分配的数组内存的耐久性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不进行数组或类的外部分配,因为我不知道它是否是一种正确的方法,如果变量的naw分配在函数外可用。

问题:是正确的将其分配到外部函数中吗?



我尝试过:



此代码适用于windows:

I do not make external allocation of arrays or classes because I do not know if it is a right way to do and if the naw allocation of the variable will be available outside the function.
Question: Is right allocate it in an external function?

What I have tried:

This code works in windows:

void external_memory_allocation_function(char **data,int size)
{
	*data=new char[size];
}


void main()
{
	char *data=NULL;
	int size=100000;
	external_memory_allocation_function(&data,size);
	char *data2=new char[size];
	for (int i=0;i<size;i++)
		data2[i]=data[i]=(char) i;
	delete[] data;
	delete[] data2;
}

推荐答案

你可以这样做,但是......

问题是什么时候释放内存。

因为分配在一个函数中隐藏,所以它不需要被删除是显而易见的,并且将函数改为不可行是非常可行的每次分配 - 它可以使用全局数组,或者例如来自更大内存块的部分分配 - 然后你的删除操作将失败。或者几次调用可以使用相同的内存 - 然后你的删除会过早地清除内存。



就个人而言,我宁愿看到配对函数,或者更好的在同一个函数中完成的分配,当它完成时删除内存。
You can do that, but...
The problem is when it comes to releasing the memory.
Because the allocation is "hidden" in a function, it isn't obvious that it needs to be deleted, and it's quite feasible that the function could be changed to not allocate each time - it could use a global array, or a partial allocation from a bigger memory chunk for example - and then your delete operation will fail. Or same memory could be used by several calls say - and then your delete will get rid of the memory prematurely.

Personally, I'd rather see either "paired" functions, or better the allocation done in the same function that deletes the memory when it's done with.


如果你在一个被调用的函数中或在调用它的代码中分配它并不重要功能。在这两种情况下,触发分配的代码(更精确:线程)拥有内存并负责释放它。



另外两个注释:



调用 delete NULL 指针>。 delete 的实现也会这样做,当指针 NULL 时,它什么都不做。



删除数组时,你应该使用 delete [] 运算符:

It does not matter if you allocate in a called function or within the code that would call the function. In both cases the code (more precise: the thread) that triggers the allocation owns the memory and is responsible for freeing it.

Two additional notes:

There is no need to check for a NULL pointer when calling delete. The implementation of delete will do that too and just does nothing when the pointer is NULL.

When deleting an array you should use the delete[] operator:
delete[] data;



你可能还要看一下C ++智能指针:

auto_ptr - C ++参考 [ ^ ]

shared_ptr - C ++参考 [ ^ ]

unique_ptr - C ++参考 [ ^ ]

weak_ptr - C ++参考 [ ^ ]


You may have also a look at C++ smart pointers:
auto_ptr - C++ Reference[^]
shared_ptr - C++ Reference[^]
unique_ptr - C++ Reference[^]
weak_ptr - C++ Reference[^]


这篇关于在外部函数中分配的数组内存的耐久性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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