如何快速释放包含动态分配内存作为值的映射?
How quickly dealocate map which contains dynamically allocated memory as a value?
Map由作为键的字符串和作为值的A的对象组成。 std::map/std::unordered_map 中的函数 clear() 不会调用析构函数。当我想清除地图时,我必须自己处理内存分配。这只是使用 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!
}
使用 std::unique_ptr
的地图,仅 clear()
。或者只在地图中保存 A
个对象而不是指针。
Map由作为键的字符串和作为值的A的对象组成。 std::map/std::unordered_map 中的函数 clear() 不会调用析构函数。当我想清除地图时,我必须自己处理内存分配。这只是使用 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!
}
使用 std::unique_ptr
的地图,仅 clear()
。或者只在地图中保存 A
个对象而不是指针。