智能指针可以与使用 new T[] 分配的数组一起使用吗?
智能指针如何处理数组?例如,
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它将调用
delete[]
,因此整个数组将被回收,但我相信您需要表明您正在使用unique_ptr
的数组形式:这被称为
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 ofunique_ptr
by:This is called as Partial Specialization of the
unique_ptr
.编辑:这个答案是错误的,正如下面的评论所解释的那样。这是我最初所说的:
我把它留在这里是因为我学到了一些东西——希望其他人也能学到一些东西。
Edit: This answer was wrong, as explained by the comments below. Here's what I originally said:
I'm leaving it here because I learned something -- hope others will too.