由于重新分配而使std :: vector的替代方法无效,从而使指向元素的指针无效 [英] Alternatives to std::vector due to reallocation that invalidates pointers to elements

查看:62
本文介绍了由于重新分配而使std :: vector的替代方法无效,从而使指向元素的指针无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个新问题(我是),但是我已经进行了尽可能多的搜索以找到以下问题的解决方案

this might be a newb question (i am) but i've searched as much as i could to find a solution to the following problem

我有以下情况(当然是高度提炼的):

I have the following scenario (heavily distilled of course):

class Container
{
std::vector<Object> obj;
};

class Pointers
{
std::vector<Object*> obj_ptr;
};

我有一个例程,将Object类型的元素推回到Container中的向量 obj ,然后将指向同一元素的指针推回到 obj_ptr .

I have a routine that pushes back an element of type Object to the vector obj in Container then pushes back the pointer to that same element to obj_ptr.

总体想法是,在程序的整个生命周期内 obj_ptr [i] == & obj [i] .

the overall idea is that obj_ptr[i] == &obj[i] throughout the life of the program.

我遇到的问题是,每当 obj 的容量需要增加时,所有指针都会失效,从而使 obj_ptr 完全无用.我已经尝试使用最大预期大小(大约10 ^ 7)并以相同的大小初始化向量,既obj.reserve().问题仍然存在.

The problem I run into is that whenever the capacity of obj needs to increase all the pointers are invalidated, making the obj_ptr completely useless. I have tried both obj.reserve() using the maximum expected size (around 10^7) and initializing the vector with that same size. Problem still persists.

不确定这是否重要,但我使用的是VS 2015 Com.

Not sure if it's important, but I'm using VS 2015 Com.

谢谢!

推荐答案

常见的替代方法是使用智能指针就像

The common alternative is using smart pointers like

class Container {
    std::vector<std::unique_ptr<Object>> obj;
};

class Container {
    std::vector<std::shared_ptr<Object>> obj;
};

(取决于您的用例).

这篇关于由于重新分配而使std :: vector的替代方法无效,从而使指向元素的指针无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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