![](/img/trans.png)
[英]Why does the map.insert() method invoke the copy constructor twice?
[英]why does returning a map.insert().second introduce unreachable memory?
以下代码:
~A()
{
for (itr = mymap.begin(); itr != mymap.end() ++itr)
{
delete itr->second //the map look like this <std::string , T*>
}
}
A::Addnew(std::string name)
{
return mymap.insert(std::pair<std::string,T*>(name, new T)).second;
}
引入内存泄漏,但如果我将AddNew()
成员函数更改为:
itr = mymap.find(name);
if(itr == mymap.end())
{
return mymap.insert(std::pair<std::string,T*>(name, new T)).second;
}
然后没有内存泄漏。
好像我不小心打了第一个案例,我会介绍很多新的T,但我的mymap.size()
无法跟踪它。 有谁能解释一下?
如果地图中已存在该键,则std::map::insert()
为无操作。
如果您尝试插入重复键,则代码的第一个版本将泄漏使用new
分配的对象。
第二个版本没有此问题,因为除非您已确定地图中不存在该键,否则不会调用new
。
解决泄漏的两种好方法是:
在您的第一个AddNew函数中:当您插入其键已存在于地图中的成员时,您将创建一个T对象,但您不会释放它:
你可以这样做:
A::Addnew(std::string name)
{
T *temp = new T;
if(mymap.insert(std::pair<std::string,T*>(name, temp)).second)
return true;
else
{
delete temp;
return false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.