I've just been looking at solutions to another question (this one). It seems that it should be possible to create a custom deleter for a unique_ptr
instance that can unlock a mutex.
For example,
#include <mutex>
#include <memory>
struct LockDeleter
{
std::unique_lock<std::mutex> lock_;
LockDeleter(std::mutex& m) : lock_(m) {}
void operator()(void*) { lock_.unlock(); }
};
int main()
{
std::mutex moo;
{
std::unique_ptr<int, LockDeleter> ptr(new int(42), LockDeleter(moo));
}
}
Compiling this under VS2013 express, I get
Error 1 error C2280: 'std::unique_lock::unique_lock(const std::unique_lock &)' : attempting to reference a deleted function
and
This diagnostic occurred in the compiler generated function 'LockDeleter::LockDeleter(const LockDeleter &)'
Now, I can't seem to force the lock deleter instance to be moved, rather than copied using std::move
... even adding an explicit move constructor to LockDeleter
doesn't help, and the deleted copy constructor still gets called.
So, am I doing something silly, or must unique_ptr
deleters always be copy constructable?