在c++中的非指针数组上的删除
当我有这样的数组时:(
int* test = new int[50];
for (int i = 0; i < 50; i++)
{
test[i] = dist4(rng);
}
填充随机数以进行测试)
我可以释放这样的内存:
delete[] test;
但是当我声明这样的数组时:
int test[50];
for (int i = 0; i < 50; i++)
{
test[i] = dist4(rng);
}
我无法使用delete或delete []释放内存。
在这里释放内存的正确方法是什么?
“ DIST4”函数只是一个随机数生成器:
random_device dev;
mt19937 rng(dev());
uniform_int_distribution<mt19937::result_type> dist4(1,4); // distribution in range [1, 4]
When I have an array like this:
int* test = new int[50];
for (int i = 0; i < 50; i++)
{
test[i] = dist4(rng);
}
(Filled with random numbers for testing)
I can free the memory like this:
delete[] test;
But when I declare the array like this:
int test[50];
for (int i = 0; i < 50; i++)
{
test[i] = dist4(rng);
}
I can't free the memory with delete or delete[].
What's the proper way of freeing the memory here?
The "dist4" function is just a random number generator:
random_device dev;
mt19937 rng(dev());
uniform_int_distribution<mt19937::result_type> dist4(1,4); // distribution in range [1, 4]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在后一种情况下,无需使用
delete
delete delete [] 明确自由存储器。假设
int test [50];
在功能中声明,它具有自动存储持续时间并且当测试
脱离范围时,它将被自动销毁。No need to free memory explicitly using
delete
ordelete[]
in the latter case.Assuming
int test[50];
is declared inside a function, it has automatic storage duration and whentest
goes out of scope it will be automatically destroyed.当内存像任何其他非动态分配变量一样,将自动释放它。这是由于自动存储时间
The memory will automatically be freed when it does out of scope like any other non-dynamically allocated variable. This is due to automatic storage duration
使用本地范围写这样的代码:
Write the code like this using a local scope: