在c++中的非指针数组上的删除

发布于 2025-02-06 08:57:23 字数 579 浏览 2 评论 0原文

当我有这样的数组时:(

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

少钕鈤記 2025-02-13 08:57:23

在这里释放内存的正确方法是什么?

在后一种情况下,无需使用delete delete delete [] 明确自由存储器。

假设int test [50];在功能中声明,它具有自动存储持续时间并且当测试脱离范围时,它将被自动销毁。

What's the proper way of freeing the memory here?

No need to free memory explicitly using delete or delete[] in the latter case.

Assuming int test[50]; is declared inside a function, it has automatic storage duration and when test goes out of scope it will be automatically destroyed.

小伙你站住 2025-02-13 08:57:23

当内存像任何其他非动态分配变量一样,将自动释放它。这是由于自动存储时间

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

拥醉 2025-02-13 08:57:23

使用本地范围写这样的代码:

void a_function ()
{

  // some code

  {
    int test[50];
    for (int i = 0; i < 50; i++)
    {
      test[i] = dist4(rng);
    }
  }
  // here the space for test will recovered.

  // some more code...

}

Write the code like this using a local scope:

void a_function ()
{

  // some code

  {
    int test[50];
    for (int i = 0; i < 50; i++)
    {
      test[i] = dist4(rng);
    }
  }
  // here the space for test will recovered.

  // some more code...

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文