[英]Use C++17 features to better delete all pointers from a container
Before C++17, deleting all pointers from a map looked like: 在C ++ 17之前,从映射中删除所有指针看起来像:
for (TMapBuffOnAttrs::iterator it = m_map_buff_on_attrs.begin(); it != m_map_buff_on_attrs.end(); it++)
{
if (NULL != it->second)
{
delete(it->second);
}
}
m_map_buff_on_attrs.clear();
With C++17, we got: 使用C ++ 17,我们得到:
for (auto it = m_map_buff_on_attrs.begin(); it != m_map_buff_on_attrs.end(); it++)
{
if (NULL != it->second)
{
delete(it->second);
}
}
Is there a simpler solution? 有没有更简单的解决方案?
Yes. 是。
for (auto it = m_map_buff_on_attrs.begin(); it != m_map_buff_on_attrs.end(); it++)
Since you only use the value *it
and no other data from that iterator, a for-range loop would be simpler. 由于只使用
*it
值*it
而没有该迭代器的其他数据,因此for-range循环会更简单。
if (NULL != it->second)
{
delete(it->second);
}
Deleting NULL
is well-defined and has no effect, this is a test you can skip. 删除
NULL
是明确定义的,并且无效,这是您可以跳过的测试。
Which gives: 这使:
for (auto& p : m_map_buff_on_attrs) {
delete p.second;
}
Manipulating raw pointers is error-prone and makes you write more useless code. 操纵原始指针容易出错,并使您编写更多无用的代码。 If
m_map_buff_on_attrs
were a map of smart pointers, your code would simply be: 如果
m_map_buff_on_attrs
是智能指针的映射,则您的代码将仅仅是:
} // m_map_buff_on_attrs goes out of scope and destroys and frees everything.
RAII pattern is your friend: RAII模式是您的朋友:
using TMapBuffOnAttrs = std::map<std::string, std::unique_ptr<Attr>>;
m_map_buff_on_attrs["attrName"] = std::make_unique<Attr>(x, a);
....
// loop is not needed, to delete just do:
m_map_buff_on_attrs.clear();
You can use for_each
with lambda
function. 您可以将
for_each
与lambda
函数一起使用。
Here is a way: 这是一种方法:
std::for_each(m_map_buff_on_attrs.begin(), m_map_buff_on_attrs.end(),
[](auto &item) {delete item.second;});
Yes, use smartpointers. 是的,请使用智能指针。 And simply 'clear()' the container... Otherwise this is just "C code written in C++17"
然后简单地'clear()'容器...否则,这仅仅是“用C ++ 17编写的C代码”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.