c++ - 如何快速释放包含动态分配内存作为值的映射?

标签 c++ c++11 pointers unordered-map stdmap

Map 由作为键的字符串和作为值的 A 的对象组成。 std::map/std::unordered_map 的函数 clear() 不会调用析构函数。当我想清除 map 时,我必须自己处理内存分配。这只是使用 for 循环释放内存的一种方法吗? 代码:

#include <iostream>
#include <unordered_map>
class A
{
public:
    A() { std::cout << "A()" << std::endl; }
    ~A() { std::cout << "~A()" << std::endl; }
};
int main ()
{
  std::unordered_map<std::string, const A*> mymap = { {"house",new A()}, {"car", new A()}, {"grapefruit", new A()} };
  //mymap.clear();//won`t call destructor
  for(const auto &i : mymap)
      delete i.second;      //dealocate value
  mymap.clear();            //clear whole object from tha map
}

是否可以更快地执行此操作,例如不使用 for 循环?

最佳答案

是的!使用 unique_ptr并将其自动化。

(请注意我是如何将 const A* 转换为 std::unique_ptr<const A> 的)

#include <iostream>
#include <memory>
#include <unordered_map>

class A {
public:
    A() { std::cout << "A()" << std::endl; }
    ~A() { std::cout << "~A()" << std::endl; }
};

int main() {
  std::unordered_map<std::string, std::unique_ptr<const A>> mymap;
  mymap["house"] = std::make_unique<A>();
  mymap["car"] = std::make_unique<A>();
  mymap["grapefruit"] = std::make_unique<A>();

  mymap.clear(); // Will call destructor!
}

关于c++ - 如何快速释放包含动态分配内存作为值的映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44987494/

相关文章:

c++ - 创建独立于构造函数参数的对象指针

c++ - 保留不可构造对象的 vector

c - ptr、*ptr 和 &ptr 之间的区别

c++ - 通过调用 CreateRemoteThread : crash 弹出 dll

c++ - 用于头文件中的匿名命名空间

c++ - 可以使 C++ 枚举大于 64 位吗?

c++ - 链接时间优化与多线程支持冲突

arrays - Rust 中指向行的指针

c++ - 我是否需要 "new"数组以便稍后执行 memset?在 C++ 中

c++ - 总帐错误 : Out of Memory when trying to render with VBO