这是删除用 new 制作的 longs 和 objects 映射的好方法吗
// iterate over the map
for (std::map<unsigned long, Object*>::iterator it = objects.begin(), it_end = objects.end(); it != it_end; ++it)
{
Object* temp = it->second;
if(temp)
delete temp;
}
// clear the map
objects.clear();
最佳答案
是的。使用 boost::ptr_map
boost::ptr_map<std::string, BigObject> data;
data.insert("Plop", new BigObject);
当数据超出范围时,它会删除其所有 value
成员。
同样对于算法,所有成员都作为对对象的引用(而不是指针)返回,因此与标准算法一起使用比需要取消引用的 std::map
有人可能会质疑,为什么您一开始就有一个指向 int/long 的指针映射?将值存储在 map 中不是更容易吗?
关于C++ 内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7095127/