简体   繁体   English

删除/删除向量项目的最有效/最快方法

[英]Most efficient/fastest way to delete/remove items of a vector

There are several ways to delete/remove items of a vector. 有几种删除/删除向量项目的方法。

I have a vector of pointers and I need to delete all of them on the deconstructor of the class. 我有一个指针向量,我需要在该类的解构函数中删除所有这些指针。

What is the most efficient/fastest way or even safest way? 什么是最有效/最快的方法,甚至最安全的方法?

// 1º
std::for_each(vector.begin(), vector.end(), [] (Object * object) {
    delete object;
});

// 2º
for (int i = 0; i < vector.size(); ++i)
{
    delete vector[i];
}

// 3º
for (auto current = vector.begin(); current != vector.end(); ++current){
    delete (* current);
}

The safest way would be to use either std::vector<std::unique_ptr<Object>> or std::vector<std::shared_ptr<Object>> depending on the lifetime semantics you need for the Object instances. 最安全的方法是使用std::vector<std::unique_ptr<Object>>std::vector<std::shared_ptr<Object>>具体取决于Object实例所需的生存期语义。

Either way, you wouldn't need to do anything in the destructor; 无论哪种方式,您都不需要在析构函数中做任何事情 the vector's destructor will destruct all of the smart pointer instances. 向量的析构函数将破坏所有智能指针实例。 In turn, they would automatically delete the Object instances according to their particular semantics: unique_ptr would delete them immediately, while shared_ptr would delete them as soon as no other shared_ptr s point to that object. 反过来,它们将根据其特定的语义自动删除Object实例: unique_ptr将立即删除它们,而shared_ptr会在没有其他shared_ptr指向该对象时立即删除它们。

It's very unlikely that there will be a faster way either, assuming that you need to store pointers. 假设您需要存储指针,也不太可能有一种更快的方法。 (If you don't need polymorphism, then you could just use std::vector<Object> which has one less level of indirection.) (如果不需要多态性,则可以只使用std::vector<Object> ,其间接级别要少一层。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM