我在发帖前查看了这个帖子:How to avoid memory leaks when using a vector of pointers to dynamically allocated objects in C++?
基本上,我有一些指向动态分配对象的指针 vector :
vector<MyType*> a;
a.push_back(new MyType());
这些 vector 是我正在编写的几个类的私有(private)实例变量,动态分配的对象在类的析构函数中通过遍历 vector 并调用 delete
来销毁。在每个指针上。
大部分时间一切正常,但每隔一段时间这些 vector 之一中的指针就会变得无效并导致 segfault
当我的代码尝试使用它时。我无法弄清楚为什么这些指针偶尔会中断。
是否有任何原因导致动态分配对象的地址发生变化并导致指针无效?
如有必要,我可以尝试发布实际代码。
编辑:
好的,我这里有很多事情要处理。有两个自定义类:VisaLane
和 VisaResource
. VisaLane
包含 vector<VisaResource*>
使用 new VisaResource()
创建的指向 VisaResources 的指针.
每个VisaLane
也是使用 new VisaLane()
创建的其指针存储在 vector<VisaLane*>
中.
这是指针如何损坏的一个示例。 vector 中的项目 0 具有不可访问的成员:
resources_ <3 items> std::vector<VisaResource*>
[0] VisaResource
function_ <not accessible> std::string
name_ <not accessible> std::string
state_ VisaResource::FREE VisaResource::VisaResourceState
value_ 6998928 uint
[1] VisaResource
function_ "lane_clksel" std::string
name_ "m1_lane0_clksel" std::string
state_ VisaResource::FREE VisaResource::VisaResourceState
value_ 0 uint
[2] VisaResource
function_ "lane_bypass" std::string
name_ "m1_lane0_bypass" std::string
state_ VisaResource::FREE VisaResource::VisaResourceState
value_ 0 uint
visa_res_itr __gnu_cxx::__normal_iterator<VisaResource**, std::vector<VisaResource*>>
最佳答案
您根本不应该使用原始指针,避免这种情况的最佳方法是使用智能指针,如果您不共享的 vector 内容,则
如果容器元素被多个实体共享。 Unique_ptr
shared_ptr
使用智能指针很可能会帮助您摆脱问题。
除了没有看到源代码之外,我们无法评论真正出了什么问题。
关于c++ - 指向动态分配对象的指针 vector : what could go wrong?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7082833/