RAII object for releasing pointer with arbitrary function The following class is a sort of "smart pointer" that can be used for automatically releasing pointers:

template &lt;class Type&gt;
class Releaser {
 public:
  Releaser(std::function&lt;void(Type *)&gt; function = [](Type *value) {
    value-&gt;Release();
  });
  ~Releaser();
  Type *operator-&gt;();
  Type &amp;operator*();
  Type *get();
  Type **fill();

 private:
  Type *value_ = nullptr;
  std::function&lt;void(Type *)&gt; function_;
};

template &lt;class Type&gt;
Releaser&lt;Type&gt;::Releaser(std::function&lt;void(Type *)&gt; function)
    : function_(function) {}

template &lt;class Type&gt;
Releaser&lt;Type&gt;::~Releaser() {
  if (value_) function_(value_);
}

template &lt;class Type&gt;
Type *Releaser&lt;Type&gt;::operator-&gt;() {
  return value_;
}

template &lt;class Type&gt;
Type &amp;Releaser&lt;Type&gt;::operator*() {
  return *value_;
}

template &lt;class Type&gt;
Type *Releaser&lt;Type&gt;::get() {
  return value_;
}

template &lt;class Type&gt;
Type **Releaser&lt;Type&gt;::fill() {
  return &amp;value_;
}


It can be used for example like this:

Releaser&lt;IMFAttributes&gt; 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 has capability for custom deleters.

Besides that assuming you are doing this to deal with COM objects then you can use ComPtr and its GetAddressOf



If you define a destructor you should also define (or disallow in this case) the copy construct and copy assign. Failure to do so will result in dangling pointers and double frees:

Releaser&lt;IMFAttributes&gt; attributes;
auto status = MFCreateAttributes(attributes.fill(), 1);
{
    Releaser&lt;IMFAttributes&gt; att = attributes;
} // att gets cleaned up

//attributes contains a dangling pointer