如何快速地将包含动态分配的内存的map映射为值?

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循环?

Cur*_*ous 5

是的!使用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)

  • @ user3455638我不遵循最后一部分,你能澄清一下你的意思吗?与缓存局部性方面的原始指针相比,`unique_ptr`解决方案几乎没有开销.它们是原始指针周围非常薄的**包装器 (3认同)