fork download
  1. #include <iostream>
  2. #include <memory>
  3. #include <vector>
  4. #include <list>
  5. #include <map>
  6. #include <string>
  7. using namespace std;
  8.  
  9. template<class T, class D>
  10. auto make_unique_ptr(T* p, D d) { return unique_ptr<T,D>(p,d); }
  11.  
  12. struct X {
  13. X(string s) : s(s) { cout << (void*)this << " -> ctor: " << s << endl; }
  14. ~X() { cout << (void*)this << " -> dtor: " << s << endl; }
  15.  
  16. string s;
  17. };
  18.  
  19. int main() {
  20. vector<X*> v;
  21. list<X*> l;
  22. map<X*,X*> m;
  23.  
  24. auto vcleaner = make_unique_ptr(&v,
  25. [](auto pvs) {
  26. for(auto v : *pvs) delete v;
  27. }
  28. );
  29.  
  30. auto lcleaner = make_unique_ptr(&l,
  31. [](auto pvs) {
  32. for(auto v : *pvs) delete v;
  33. }
  34. );
  35.  
  36. auto mcleaner = make_unique_ptr(&m,
  37. [](auto pkvs) {
  38. for(const auto& kv : *pkvs) {
  39. delete kv.first;
  40. delete kv.second;
  41. }
  42. }
  43. );
  44.  
  45. cout << "---- fill the map ----" << endl;
  46. m[new X("k1")] = new X("w1");
  47. m[new X("k2")] = new X("w2");
  48. cout << "---- fill the vector ----" << endl;
  49. v.push_back(new X("v1"));
  50. v.push_back(new X("v2"));
  51. cout << "---- fill the list ----" << endl;
  52. l.push_back(new X("l1"));
  53. cout << "---- release the vector ----" << endl;
  54. vcleaner.release();
  55. cout << "---- goodbye! ----" << endl;
  56.  
  57. // your code goes here
  58. return 0;
  59. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
---- fill the map ----
0x88f4a28 -> ctor: w1
0x88f4a50 -> ctor: k1
0x88f4a98 -> ctor: w2
0x88f4ac0 -> ctor: k2
---- fill the vector ----
0x88f4b08 -> ctor: v1
0x88f4b40 -> ctor: v2
---- fill the list ----
0x88f4b18 -> ctor: l1
---- release the vector ----
---- goodbye! ----
0x88f4a50 -> dtor: k1
0x88f4a28 -> dtor: w1
0x88f4ac0 -> dtor: k2
0x88f4a98 -> dtor: w2
0x88f4b18 -> dtor: l1