use*_*638 1 c++ pointers unordered-map stdmap c++11
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
}
Run Code Online (Sandbox Code Playgroud)
是否可以更快地完成此操作,例如不使用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!
}
Run Code Online (Sandbox Code Playgroud)