智能指针可以与使用 new T[] 分配的数组一起使用吗?

发布于 2024-11-24 05:06:53 字数 197 浏览 7 评论 0原文

智能指针如何处理数组?例如,

void function()
{
    std::unique_ptr<int> my_array(new int[5]);
}

当 my_array 超出范围并被破坏时,整个整数数组是否会被重新声明?只回收数组的第一个元素吗?或者还有其他事情发生(例如未定义的行为)?

How do smart pointers handle arrays? For example,

void function()
{
    std::unique_ptr<int> my_array(new int[5]);
}

When my_array goes out of scope and gets destructed, does the entire integer array get re-claimed? Is only the first element of the array reclaimed? Or is there something else going on (such as undefined behavior)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

ˉ厌 2024-12-01 05:06:56

它将调用delete[],因此整个数组将被回收,但我相信您需要表明您正在使用unique_ptr的数组形式:

std::unique_ptr<int[]> my_array(new int[5]);

这被称为unique_ptr部分专业化

It will call delete[] and hence the entire array will be reclaimed but I believe you need to indicate that you are using an array form of unique_ptrby:

std::unique_ptr<int[]> my_array(new int[5]);

This is called as Partial Specialization of the unique_ptr.

若无相欠,怎会相见 2024-12-01 05:06:56

编辑:这个答案是错误的,正如下面的评论所解释的那样。这是我最初所说的:

我认为 std::unique_ptr 不知道调用delete[]。它有效地
有一个 int* 作为成员——当你删除一个 int* 时,它会
删除整个数组,所以在这种情况下就可以了。

与普通删除相比,delete[] 的唯一目的是
它调用数组中每个元素的析构函数。对于原始的
类型并不重要。

我把它留在这里是因为我学到了一些东西——希望其他人也能学到一些东西。

Edit: This answer was wrong, as explained by the comments below. Here's what I originally said:

I don't think std::unique_ptr knows to call delete[]. It effectively
has an int* as a member -- when you delete an int* it's going to
delete the entire array, so in this case you're fine.

The only purpose of the delete[] as opposed to a normal delete is that
it calls the destructors of each element in the array. For primitive
types it doesn't matter.

I'm leaving it here because I learned something -- hope others will too.

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