September 2017
Beginner to intermediate
384 pages
9h 18m
English
Speaking of custom RAII types, you might be wondering whether it's possible to use std::unique_ptr with a customized deletion callback: for example, instead of passing the underlying pointer to delete, you might want to pass it to free(). Yes you can!
std::unique_ptr<T,D> has a second template type parameter: a deletion callback type. The parameter D defaults to std::default_delete<T>, which just calls operator delete, but you can pass in any type you want--typically a user-defined class type with an overloaded operator():
struct fcloser { void operator()(FILE *fp) const { fclose(fp); } static auto open(const char *name, const char *mode) { return std::unique_ptr<FILE, fcloser>(fopen(name, mode)); } };Read now
Unlock full access