简体   繁体   English

为什么返回map.insert()。第二次引入无法访问的内存?

[英]why does returning a map.insert().second introduce unreachable memory?

The following code: 以下代码:

  ~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;
    }

introduces a memory leak, but if I change the AddNew() member function to: 引入内存泄漏,但如果我将AddNew()成员函数更改为:

itr = mymap.find(name);
if(itr == mymap.end())
{
   return mymap.insert(std::pair<std::string,T*>(name, new T)).second;
}

then there is no memory leak. 然后没有内存泄漏。

It seems like if I called the first case accidentally, I will introduce lots of new T, but my mymap.size() cannot keep track of it. 好像我不小心打了第一个案例,我会介绍很多新的T,但我的mymap.size()无法跟踪它。 Can anyone explain this? 有谁能解释一下?

std::map::insert() is a no-op if the key already exists in the map. 如果地图中已存在该键,则std::map::insert()为无操作。

If you try to insert a duplicate key, the first version of your code will leak the object it has allocated using new . 如果您尝试插入重复键,则代码的第一个版本将泄漏使用new分配的对象。

The second version does not have this problem since you don't call new unless you've established that the key doesn't exist in the map. 第二个版本没有此问题,因为除非您已确定地图中不存在该键,否则不会调用new

Two good ways to fix the leak are: 解决泄漏的两种好方法是:

  • store the objects by value; 按值存储对象;
  • store smart pointers to objects. 存储对象的智能指针。

In your first AddNew function: when you are inserting a member whose key have existed in the map, you will create a T object,but you do not release it: 在您的第一个AddNew函数中:当您插入其键已存在于地图中的成员时,您将创建一个T对象,但您不会释放它:

you can do like this: 你可以这样做:

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.

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