如何擦除包含包含结构的地图结构的地图?

时间:2013-11-11 21:45:09

标签: c++

我有以下代码用于创建包含结构地图的结构的地图。我的问题是如何从providerMap中删除一个元素而不会留下任何内存泄漏。我可以只做一个providerMap [prov_id] .erase(),还是我需要对第二个或更复杂的东西进行删除?

struct uriPrivs {
    std::string name;
    uchar properties;
};
struct providerValues {
    int KeepAlive;
    std::map<std::string /*uri*/, uriPrivs> uris;
};
std::map<std::string /*prov_id*/, providerValues> providerMap;

RISStorageManager::risStorageResponse RISStorageManager::update_provider(const std::string &prov_id, int KeepAlive) {

    if (providerMap.find(prov_id) == providerMap.end()) {
        providerValues x;
        x.KeepAlive = KeepAlive;
        providerMap[prov_id] = x;
        return risStorageCreated;
    } else {
        providerMap[prov_id].KeepAlive = KeepAlive;
        return risStorageUpdated;
    }
}
RISStorageManager::risStorageResponse RISStorageManager::update_uri(const std::string &prov_id, std::map<std::string, uriPrivs> &uris) {
    providerMap[prov_id].uris = uris;
}

1 个答案:

答案 0 :(得分:4)

如前所述,您不需要在此处显式释放任何内存。你自己并不是“新手”。一切都将由地图对象的析构者处理。

你可以稍微压缩update_provider函数......

RISStorageManager::risStorageResponse update_provider(const std::string &prov_id, int KeepAlive)
{
   RISStorageManager::risStorageResponse response = (providerMap.end() == providerMap.find(prov_id)) ?
      risStorageCreated : risStorageUpdated;

   providerMap[prov_id].KeepAlive = KeepAlive;

   return response;
}

这里有一些测试代码可以解释一些事情......

int main(int argc, char *argv [])
{
   // Create new provider and print result...
   std::cout << update_provider("test1", 1) << std::endl;

   // Add a URI to the first provider for fun...
   providerMap["test1"].uris["www.google.com"].name = "GOOGLE";
   providerMap["test1"].uris["www.google.com"].properties = 0xFF;

   // Create new provider and print result...
   std::cout << update_provider("test2", 1) << std::endl;

   // Create new provider and print result...
   std::cout << update_provider("test3", 1) << std::endl;

   // Update first provider and print result...
   std::cout << update_provider("test1", 0) << std::endl;

   // Explicitly remove first provider if you want...
   providerMap.erase("test1");

   //
   // Now only 2 providers are in map (test2 and test3).
   // The program will exit and the STL map destructors will take care of any
   // memory deallocation that is needed to clean up the maps. You don't need
   // to explicitly clean up anything unless you want to remove providers from
   // your map explicitly.
   //

   return 0;
}