智能指针和数组 [英] smart pointers and arrays

查看:587
本文介绍了智能指针和数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do smart pointers handle arrays? For example,

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

my_array 超出范围并被破坏,整个数组是否会被重新声明?只是数组的第一个元素被回收?

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)?

推荐答案

它会调用 delete [ ] ,因此整个数组将被回收,但我相信你需要指出你正在使用 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 a array form of unique_ptrby:

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

这称为部分专业化 unique_ptr

This is called as Partial Specialization of the unique_ptr.

这篇关于智能指针和数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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