我有一个要删除的指针向量,但是遍历向量并调用delete
每个元素非常慢。有更快的方法吗?
不幸的是,我真的需要存储指针,因为我使用了一个虚拟超类。简化后,类结构看起来像这样:
class VirtualSuperClass
{
protected:
SomeType m_someMember;
// ...
public:
virtual void doSomething() = 0;
};
class Subclass_1 : public VirtualSuperClass
{
protected:
SomeType m_someSubclassMember;
// ...
public:
virtual void doSomething() { /* do something*/ }
};
class Subclass_2 : public VirtualSuperClass
{
protected:
SomeType m_someOtherSubclassMember;
// ...
public:
virtual void doSomething() { /* do something else*/ }
}
在我的主要方法中,我填充了超类的指针向量并doSomething()
为每个元素调用函数。
int main()
{
std::vector<VirtualSuperClass*> vec;
vec.push_back(new Subclass_1());
vec.push_back(new Subclass_2());
vec.push_back(new Subclass_2());
vec.push_back(new Subclass_1());
// and so on, about 40,000 elements (not really done with .push_back :) ) ...
// this actually runs in an application loop
for (size_t i = 0; i < vec.size(); i++)
{
vec[i]->doSomething();
}
// ...
for (size_t i = 0; i < vec.size(); i++)
{
delete vec[i]; // <-- pretty slow for large number of elements
vec[i] = NULL;
}
vec.clear();
return 0;
}