唯一/共享ptr,在超出范围后自动删除数组

时间:2017-05-09 20:39:02

标签: c++ c++11

我正在努力提高我的C ++技能。假设我有以下代码

#include <iostream>

using namespace std;

int main()
{
    int *p;
    p=new int[10];
    delete [] p;
    return 0;
}

如果在这段代码中超出范围,我如何使用unique / shared ptr自动删除数组而不是手动执行?BTW我已经读过SO,我可能需要下载boost库来使用unique / shared ptr。任何人都可以确认这个吗?或者它是否包含在std库中?

2 个答案:

答案 0 :(得分:4)

C ++ 11中有std::unique_ptr<T[]>,允许您这样做:

std::unique_ptr<int[]> p(new int[10]);

如果需要编译时常量数组,可以使用std::array代替:

std::array<int, 10> p;

否则,只需选择好的旧std::vector

std::vector<int> p(10);

答案 1 :(得分:3)

自C ++ 11起,std::unique_ptr包含在标准库中。你可以这样做:

#include <memory>

int main()
{
    std::unique_ptr<int[]> p( new int[10] );
}

顺便说一下,using namespace std; is a bad habit进入。

您也可以考虑使用std::vector<int>代替std::unique_ptr<int[]>