首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >可以声明一个指向堆栈上std::vector<int>的智能指针数组吗?

可以声明一个指向堆栈上std::vector<int>的智能指针数组吗?
EN

Stack Overflow用户
提问于 2019-09-01 21:49:36
回答 1查看 256关注 0票数 1

可以在堆栈上声明一个固定大小的原始指针数组,该数组可用于在运行时动态分配内存(对象)。我试图用智能指针替换原始指针,但是这个模式失败了。

下面的代码总结了这个问题,希望它不会太冗长:

代码语言:javascript
复制
#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数组的智能指针,即:

代码语言:javascript
复制
    //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
    }

据我所知,这不是智能指针所支持的吗?:

代码语言:javascript
复制
    //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。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-01 21:57:00

//旧方法用于声明带有//内存泄漏风险的std::向量指针数组,使用//数组指针的自动(基于堆栈的)分配,对向量使用动态(基于堆的)分配:

自动存储持续时间数组不会泄漏。然而,它们的元素可以。例如,当它们是指向动态分配元素的指针时。智能指针是用来替换原始指针的,所以也是这样做的--用例如std::unique_ptr<T>替换std::unique_ptr<T>。不要用智能指针替换自动存储持续时间数组--最多使用std::array。我相信你是在寻找这样的东西:

代码语言:javascript
复制
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";          
    }     
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57749737

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档