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/