You have pointers to local variables. Local variables exists on the stack only while the function runs, when the function returns those objects are destroyed and their destructors called. The memory those object occupied will after the function returns be reused by the next function to be called. This means that the pointers you have not only points to possibly destructed objects, the can also point to memory being used for something completely different. The same goes for references of course.
Allocate those objects on the heap with new
instead, or use smart pointers.
You can call specific constructors of objects in your class in your constructors initializer list:
class cache
{
public:
cache(const std::string& lock_name)
: mutex_(open_only, lock_name),
cache_lock_(mutex_, defer_lock)
{}
// ...
private:
named_mutex mutex_;
scoped_lock<named_mutex> cache_lock_;
// ...
};