This is becoming a common pattern in my code, for when I need to manage an object that needs to be noncopyable because either A. it is \"heavy\" or B. it is an operating sys
Use a boost::intrusive_ptr which is designed to work on a class with an embedded reference count.
Non-tested example based on example here:
class Resource;
class Implementation : public boost::noncopyable
{
friend class Resource;
HANDLE someData;
int refCount; // The reference count.
Implementation(HANDLE input) : someData(input) { refCount = 0; };
void SomeMethodThatActsOnHandle() {
//Do stuff
};
public:
~Implementation() { FreeHandle(someData) };
};
intrusive_ptr_add_ref(Implementation* imp) { imp->refCount++; }
intrusive_ptr_release(Implementation* imp) { if(--imp->refCount) == 0) delete imp; }
class Resource
{
boost::intrusive_ptr impl;
public:
Resource(int argA) explicit {
HANDLE handle =
SomeLegacyCApiThatMakesSomething(argA);
if (handle == INVALID_HANDLE_VALUE)
throw SomeTypeOfException();
impl.reset(new Implementation(handle));
};
void SomeMethodThatActsOnTheResource() {
impl->SomeMethodThatActsOnTheHandle();
};
};