可以在堆栈上声明一个固定大小的原始指针数组,该数组可用于在运行时动态分配内存(对象)。我试图用智能指针替换原始指针,但是这个模式失败了。
下面的代码总结了这个问题,希望它不会太冗长:
#include <iostream>
#include <vector>
#include <memory>
const int SIZE = 10;
//older method of declaring an array of std::vector<int> pointers with
//memory leak risks, using automatic (stack-based) allocation for the
//array of pointers, dynamic (heap-based) allocation for the vectors:
std::vector<int>* arr[SIZE];
for (int i = 0; i < SIZE; i++) {
arr[i] = new std::vector<int>;
}
for (int i = 0; i < SIZE; i++) {
arr[0]->push_back(i);
}
for (int val : *arr[0]) {
std::cout << val << " "; //prints 0 - 9 as expected
}这与往常一样有效,但在尝试实现智能指针时,我只能获得一个指向std::vector数组的智能指针,即:
//declaring smart pointer to an array of std::vector<int>, which is not
//automatic (stack-based) allocation of the array
std::unique_ptr<std::vector<int>[]> arr2 (new std::vector<int>[SIZE]());
for (int i = 0; i < SIZE; i++) {
arr2[0].push_back(i);
}
for (int val : arr2[0]) {
std::cout << val << " "; //prints 0 - 9 as expected
}据我所知,这不是智能指针所支持的吗?:
//attempting to declare an array of smart pointers to std::vector<int>
std::unique_ptr<std::vector<int>> arr3[SIZE];
for (int i = 0; i < SIZE; i++) {
std::cout << &arr3[i] << std::endl; //prints memory locations
if (arr3[i]->empty()) { //seg faults @ runtime
std::cout << "empty vector\n";
}
arr3[i] = new std::vector<int>; //won't compile
}(请告诉我这种模式是否也存在基本问题)
在最后一个代码块中,arr3似乎得到了分配的内存,但我不知道如何使用它来创建一个新的std::vector。
发布于 2019-09-01 21:57:00
//旧方法用于声明带有//内存泄漏风险的std::向量指针数组,使用//数组指针的自动(基于堆栈的)分配,对向量使用动态(基于堆的)分配:
自动存储持续时间数组不会泄漏。然而,它们的元素可以。例如,当它们是指向动态分配元素的指针时。智能指针是用来替换原始指针的,所以也是这样做的--用例如std::unique_ptr<T>替换std::unique_ptr<T>。不要用智能指针替换自动存储持续时间数组--最多使用std::array。我相信你是在寻找这样的东西:
std::unique_ptr<std::vector<int>> arr3[SIZE];
// or better - std::array<std::unique_ptr<std::vector<int>>, SIZE> arr3{};
for (int i = 0; i < SIZE; i++) {
arr3[i] = std::make_unique<std::vector<int>>(); // notice the syntax...
// ... and the fact that you first allocate the vector, *then* use the ->empty()
std::cout << &arr3[i] << std::endl;
if (arr3[i]->empty()) {
std::cout << "empty vector\n";
}
}https://stackoverflow.com/questions/57749737
复制相似问题