Kai*_*elm 1 c++ memory pointers new-operator
这是删除使用new创建的longs和object的地图的好方法
// 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();
Run Code Online (Sandbox Code Playgroud)
Mar*_*ork 10
是.使用boost :: ptr_map
boost::ptr_map<std::string, BigObject> data;
data.insert("Plop", new BigObject);
Run Code Online (Sandbox Code Playgroud)
当数据超出范围时,它会删除其所有value成员.
此外,对于算法,所有成员都作为对象(不是指针)的引用返回,因此使用标准算法比使用std :: map <std :: string,BigObject*>更容易去除使用前的memebrs.
人们不得不质疑为什么你有一个指向int/long的指针的地图?将值存储在地图中会不会更容易?