如何从对象指针的向量中正确清理元素
How to properly clean up elements from vectors of object pointers
我一直在研究动态分配,并在StackOverflow上遇到了这个问题:
解除分配存储在矢量中的对象?
其中一个投票的答案解释了在使用"指向对象的指针向量"时如何手动管理内存:遍历调用删除的向量。
我的问题是关于如何删除向量的特定元素,而不是整个向量。在下面的示例程序中,我有一个对象指针向量。想象一下,这些对象的 x 变量随着时间的推移而递减......当对象的 x 值达到一个数字(假设 3)时,我希望删除该对象;但是,我想始终保持向量可按对象的 x 值排序。
问题是,当我对 x 值达到 3 的对象调用 delete 时,对象被删除,但那里仍然有一个指向随机内存位置的指针,并且向量的大小也保持不变。
当我遍历打印 x 值的矢量时,我调用 delete 的元素仍然存在,但指向 -53408995 之类的值。如何摆脱矢量的指针元素以及对象?
调用 erase 不是一种选择,因为在我的实际程序中(不是下面的最小示例),向量由改变 x 值等价物的其他因素连续排序。我无法跟踪他们的索引。我想在遍历矢量以检查 x 值时删除对象和指针元素。
例:
#include <iostream>
#include <vector>
class A
{
public:
A(int i) { x = i; }
int x;
};
int main()
{
std::vector<A*> Vec;
Vec.push_back(new A{ 5 });
Vec.push_back(new A{ 4 });
Vec.push_back(new A{ 3 });
std::cout << "Size before = " << Vec.size() << std::endl; // 3
for (auto& a : Vec)
{
std::cout << a->x << std::endl;
if (a->x == 3) { delete a; }
}
std::cout << "Size after = " << Vec.size() << std::endl; // Still 3!
for (auto& a : Vec)
{
std::cout << a->x << std::endl; // Prints 5, 4 and a random memory location like -34528374
}
return 0;
}
您在注释中提到对象将具有指向它们的其他指针。 这对我来说听起来很std::shared_ptr<A>
。 这样,您就可以获得指向A
对象的其他指针,而不会出现内存泄漏问题。(std::shared_ptr
附带少量(!)性能成本,但您现在不必担心)。 此外,我更改了您的段落以从矢量中删除/擦除您的元素。请注意,如果还有其他实例保留std::shared_ptr<A>
副本,则A
对象仍然处于活动状态(但这是一件好事)。
这是代码:
#include <iostream>
#include <vector>
#include <memory>
#include <algorithm>
class A
{
public:
A(int i) { x = i; }
int x;
};
int main()
{
std::vector<std::shared_ptr<A>> Vec;
Vec.emplace_back(std::make_shared<A>(5));
Vec.emplace_back(std::make_shared<A>(4));
Vec.emplace_back(std::make_shared<A>(3));
std::cout << "Size before = " << Vec.size() << std::endl;
Vec.erase(
std::remove_if(std::begin(Vec),std::end(Vec), [](auto&& ptr){ return ptr->x == 3;}),
std::end(Vec));
std::cout << "Size after = " << Vec.size() << std::endl;
for (auto&& a : Vec)
{
std::cout << a->x << std::endl;
}
return 0;
}
在这种情况下,您必须使用std::list容器
#include <iostream>
#include <list>
class A
{
public:
A(int i) { x = i; }
int x;
};
int main()
{
std::list<A*> Vec;
Vec.push_back(new A{ 5 });
Vec.push_back(new A{ 4 });
Vec.push_back(new A{ 3 });
std::cout << "Size before = " << Vec.size() << std::endl;
for (auto& a : Vec)
{
std::cout << a->x << std::endl;
}
Vec.remove_if([](A* a){
bool status = (a->x == 3);
if(status){
delete a;
return true;
}else{
return false;
}
});
std::cout << "Size after = " << Vec.size() << std::endl;
for (auto& a : Vec)
{
std::cout << a->x << std::endl;
}
return 0;
}
输出:
Size before = 3
5
4
3
Size after = 2
5
4
我重写了您的代码,添加了一些改进
#include <iostream>
#include <list>
class A
{
public:
A(const int& i):x(i) {} // so X is assigned to i in construction ( more efficient )
int get_x() const {return x;}
private:
int x; // x have to be private ( good practice )
};
int main()
{
std::list<A> List; // A instead of A* so the process of construction / destruction is handled automatically
List.emplace_back(5); // append element and constructed at the same time
List.emplace_back(4); // see std::list for more details
List.emplace_back(3);
std::cout << "Size before = " << List.size() << std::endl;
for (auto& a : List)
{
std::cout << a.get_x() << std::endl;
}
List.remove_if([](A a){ return a.get_x() == 3;});
std::cout << "Size after = " << List.size() << std::endl;
for (auto& a : List)
{
std::cout << a.get_x() << std::endl;
}
return 0;
}
std::vector<std::unique_ptr<A>> vec;
这将处理正常删除并通过异常退出。
在研究了迭代器之后,我还想出了一个使用原始指针的答案:
for (std::vector<A*>::iterator it = Vec1.begin(); it != Vec1.end(); )
{
if ((*it)->x == 3)
{
delete * it;
it = Vec1.erase(it);
}
else
{
++it;
}
}
我将保留phön的帖子作为答案,因为如果可用,智能指针应始终优先于原始指针。
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- C++:如何循环通过向量中的整数元素
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- 不允许在向量中添加更多元素
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 使用并行参数向量调用元素向量的成员函数
- C++ 查找字符串中存在的元素向量
- 包含 std::threads 的元素向量
- 避免从单一元素向量转换为基元类型
- 对自定义元素向量进行排序时出现意外(至少对我来说)行为
- 如何为对元素(向量和int)配对创建unique_ptr也是unique_ptr
- 元素向量乘法 C++(代码不起作用)
- 时间和空间复杂性在二叉树的每个级别创建元素向量(NON-BST)
- 遍历结构元素向量
- 犰狳C++中的元素向量或矩阵乘法
- 为什么'std::vector<int> b{2};'创建 1 元素向量,而不是 2 元素向量?
- 可移动元素向量的大小调整是否有效?
- 唯一元素向量的c++模板函数
- 获取索引和元素-向量问题
- 定义一个生成元素向量的函数时,正确的方法是什么?