如何创建通用 std::vector 析构函数?
拥有一个包含指向对象的指针的向量,然后使用clear函数不会调用向量中对象的析构函数。 我创建了一个函数来手动执行此操作,但我不知道如何使其成为向量中可能存在的任何类型对象的通用函数。
void buttonVectorCleanup(vector<Button *> dVector){
Button* tmpClass;
for(int i = 0; i < (int)dVector.size(); i++){
tmpClass = dVector[i];
delete tmpClass;
}
}
这是我拥有的函数,适用于向量中特定类型的对象,但我想要一个可以采用带有对象指针的任何类型向量的函数。
Having a vector containing pointers to objects then using the clear function doesn't call the destructors for the objects in the vector. I made a function to do this manually but I don't know how to make this a generic function for any kind of objects that might be in the vector.
void buttonVectorCleanup(vector<Button *> dVector){
Button* tmpClass;
for(int i = 0; i < (int)dVector.size(); i++){
tmpClass = dVector[i];
delete tmpClass;
}
}
This is the function I have that works fine for a specific type of object in the vector but I'd like a single function that could take any kind of vector with object pointers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能想使用 boost 的指针容器 。 它们高效且安全。
You might want to use boost's pointer containers. They are highly efficient and safe.
最好的办法是使用智能指针,例如来自 Boost 。 然后对象将被自动删除。
或者你可以制作一个模板函数
}
The best thing to do is use smart pointers, such as from Boost. Then the objects will be deleted automatically.
Or you can make a template function
}
其他几点 - 您可能想传递对向量的引用,而不是副本。 不需要 tmpClass - 您可以直接删除指针。 您应该在删除后将向量的大小调整为 0 或将指针替换为 NULL - 否则您可以在调用函数中访问未分配的内存。
A couple of other points - you probably want to pass a reference to the vector, not a copy. tmpClass is not needed - you can delete the pointer directly. You should either resize the vector to 0 or replace the pointers with NULL after deleting - otherwise you could access unallocated memory in the calling function.
我使用一个特殊的函子来删除指针并将其设置为 NULL:
它与
std::for_each
一起使用(也不要忘记#include
):I use a special functor to delete the pointer and set it to NULL:
Which is used with
std::for_each
(also don't forget to#include <algorithm>
):