The following class is a sort of "smart pointer" that can be used for automatically releasing pointers:
template <class Type>
class Releaser {
public:
Releaser(std::function<void(Type *)> function = [](Type *value) {
value->Release();
});
~Releaser();
Type *operator->();
Type &operator*();
Type *get();
Type **fill();
private:
Type *value_ = nullptr;
std::function<void(Type *)> function_;
};
template <class Type>
Releaser<Type>::Releaser(std::function<void(Type *)> function)
: function_(function) {}
template <class Type>
Releaser<Type>::~Releaser() {
if (value_) function_(value_);
}
template <class Type>
Type *Releaser<Type>::operator->() {
return value_;
}
template <class Type>
Type &Releaser<Type>::operator*() {
return *value_;
}
template <class Type>
Type *Releaser<Type>::get() {
return value_;
}
template <class Type>
Type **Releaser<Type>::fill() {
return &value_;
}
It can be used for example like this:
Releaser<IMFAttributes> attributes;
auto status = MFCreateAttributes(attributes.fill(), 1);
where MFCreateAttributes
has the following signature:
MFCreateAttributes(IMFAttributes** ppMFAttributes, unsigned int cInitialSize);
Do you see any way to improve this (e.g by getting rid of the std::function), or make it safer?
unique_ptr
supports custom deleters. Though the deleter type will leak into the template arguments (which can be alleviated using a typedef). \$\endgroup\$ – ratchet freak Sep 23 '16 at 10:51