我一直在研究动态分配,并在StackOverflow上遇到了这个问题:
Deallocating objects stored in a vector?
其中一个热烈的答案解释了当使用“指向对象的指针”时如何手动管理内存:迭代调用删除的向量。
我的问题是如何删除矢量的特定元素,而不是整个矢量。在下面的示例程序中,我有一个对象指针向量。想象一下,这些对象的x变量随着时间的推移而递减......当一个对象的x值达到一个数字(假设为3)时,我希望删除该对象;但是,我想保持矢量SORTABLE始终为对象的x值。
问题在于,当我对x值达到3的对象调用delete时,对象被删除但是仍有一个指向随机内存位置的指针,并且向量的大小也保持不变。
当我遍历矢量打印x值时,我调用delete的元素仍然存在但指向像-53408995这样的值。如何摆脱向量的指针元素以及对象?
调用擦除不是一种选择,因为在我的实际程序中(不是下面的最小示例),矢量会被其他因素改变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;
}
答案 0 :(得分:3)
您在评论中提到对象将有其他指针。这对我来说听起来像std::shared_ptr<A>
。通过这种方式,您可以在没有内存泄漏问题的情况下获得指向A
对象的其他指针。 (std::shared_ptr
带有很小的(!)性能成本,但你现在不用担心它。
另外我改变了你的段落,从矢量中删除/删除你的元素。请注意,如果有其他实例保留A
副本,std::shared_ptr<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;
}
答案 1 :(得分:2)
在这种情况下,您必须使用 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;
}
答案 2 :(得分:1)
std::vector<std::unique_ptr<A>> vec;
这将处理正常删除并通过异常退出。
答案 3 :(得分:0)
在研究了迭代器之后,我还想出了一个使用原始指针的答案:
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的帖子作为答案,因为智能指针应始终优先于原始指针(如果可用)。