I need smart pointer-like behaviour - to execute arbitrary code when an object goes out of scope. Another example would be std::lock_guard
that would call unlock()
on a mutex object when it goes out of scope.
Is there any standard C++ classes that can do something like:
FILE *fp = fopen("foo.txt", "w");
...
DyingWish d( [&fp]() { fclose(fp); } );
//now when 'd' goes out of scope, fclose() will be called on fp
I found that std::unique_ptr
accepts a custom deleter functor.
So, I can do:
std::unique_ptr<void, std::function<void (void*)> d(nullptr, [&fp]() { fclose(fp); });
But unique_ptr
will call invoke the deleter only if the pointer is not null. So I need to do a hack like:
std::unique_ptr<void, std::function<void (void*)> d((void*)1, [&fp]() { fclose(fp); });
OR
std::unique_ptr<void, std::function<void (void*)> d(nullptr, [&fp]() { fclose(fp); });
p.reset((void*)p);
The above code obviously is verbose, hackish and messy.
Is there any standard C++ class with which I can accomplish this (similar to the DyingWish use case above)? I would like to avoid writing a class for this. I am fine with a using
declaration though.
I can do:
using DyingWish = std::unique_ptr<void, std::function<void (void*)>;
But that too requires the hack to avoid the null pointer problem, and also a useless first argument.