我可以通过for_each< algorithm>在C ++中的指针向量上调用delete吗? [英] Can I call `delete` on a vector of pointers in C++ via for_each <algorithm>?
问题描述
std :: vector< Obj *> objs
(因为性能的原因,我有指针不是实际 Obj
s)。 用 obj.push_back(new Obj(...));
来填充它。
,我必须删除
推回的元素。一种方法是这样做的:
$ p $
for(std :: vector< Obj *> :: iterator it = objs.begin (); it!= objs.end(); ++ it){
delete * it;
$ / code> 然而,如果我可以使用 for_each 算法做同样的事情:
#include< algorithm>
...
for_each(objs.begin(),objs.end(),delete);
您怎么看?
解决方案你的问题是, delete
不是一个函数,而是一个关键字,因此你不能把它的地址。
在C ++ 0x中,会有一个 std :: default_delete
类(由 std使用你可以使用它,或者 - 正如所有人所说的那样 - 自己写一个将是微不足道的(如果你试图删除一个不完整的类型,标准的也会产生一个编译错误)。 / p>
#include< vector>
#include< algorithm>
#include< memory>
int main()
{
std :: vector< int *> VEC;
std :: for_each(vec.begin(),vec.end(),std :: default_delete< int>());
}
Suppose I have a std::vector<Obj *> objs
(for performance reasons I have pointers not actual Obj
s).
I populate it with obj.push_back(new Obj(...));
repeatedly.
After I am done, I have to delete
the pushed-back elements. One way is to do this:
for (std::vector<Obj *>::iterator it = objs.begin(); it != objs.end(); ++it) {
delete *it;
}
However, I am interested if I can use for_each
algorithm to do the same:
#include <algorithm>
...
for_each(objs.begin(), objs.end(), delete);
What do you think?
解决方案 Your problem is that delete
is not a function, but rather a keyword and as such you can't take it's address.
In C++0x, there will be a std::default_delete
class (used by std::unique_ptr
), which you could use, or - as everyone's saying - writing one yourself would be trivial (the standard one also raises a compile error, if you try to delete an incomplete type).
#include <vector>
#include <algorithm>
#include <memory>
int main()
{
std::vector<int*> vec;
std::for_each(vec.begin(), vec.end(), std::default_delete<int>());
}
这篇关于我可以通过for_each< algorithm>在C ++中的指针向量上调用delete吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文