Storing a unique_ptr with custom deleter in a map

  • A+
Category:Languages

Why doesn't this work?

#include <map> #include <memory>  void deleter(int* i) {     delete i; }  std::map<int, std::unique_ptr<int, decltype(&deleter)>> m;  void foo(int* i) {     m[0] = std::unique_ptr<int, decltype(&deleter)>(i, &deleter); } 

Check out the incomprehensible compile error https://godbolt.org/z/Uhp9NO.

 


The problem is that m[0] calls the default constructor of std::unique_ptr<int, decltype(&deleter)>, which is not available because it requires the deleter pointer.

Fix:

struct Deleter {     void operator()(int* i) { delete i; } };  std::map<int, std::unique_ptr<int, Deleter>> m;  void foo(int* i) {     m[0] = std::unique_ptr<int, Deleter>(i); } 

This is also more efficient than std::unique_ptr<int, decltype(&deleter)> because it does not have to store the very same pointer to deleter in each instance of std::unique_ptr. I.e. sizeof(std::unique_ptr<int, Deleter>) < sizeof(std::unique_ptr<int, decltype(&deleter)>).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: