Thursday, June 14, 2007

think carefully about copying behaviour in resource managing classes

for non heap based resources smart pointers like auto_ptr and tr1:;shread_ptr are generally inappropriate as resource handlers. you can just create your own resource managing classes for this purpose.

for e.g. mutex handler class, that acquires mutex while it is initializing in the constructor and releases the mutex in the destructor of the class.


now you need to worry about the copying behavior of this classes

general question we discuss is what happens when a raii class is copied. some options are :
prohibit copying: does it makes sense to allow copying of the object.( see item 6 on how to do it)

reference count the underlying source: if you want to hold on to a resource until the last object using it has been destroyed....similar copy meaning as in tr1..shared..in this case u can implement it using a data member of tr1..shared

talking of mutex for second case....tr1 will delete it by default ( though we want to release lock when reference count goes to zero)... hey you can specify a deleter function for tr1::shared_ptr....its not available for auto_ptr though

class lock {
public:
explicit Lock(mutex* pm) : mutexPtr(pm, unlock) { lock(mutexptr.get() }
private :
std::tr1_shared_ptr mutexPtr;
};
note that unlock is the deleter function here

note that when count will go to zero the mutex wud automatically get deleted....lock destroyed->tr1 destructor -> unlock function

Third way out is : copy the underlying resource:
if having multiple copies is okay and you choose resource managing class so that any allocated resource is always freed ...u shud be a doing a deep copy.

fourth option is : transfer ownership of the underlying resource...like auto_ptrs.

things to remember:
copying an raii objects entails copying the resource it manages, so the copying behavior of the resource determines the copying behavior of the raii object

common raii class copying behaviors are disallowing copying and performing reference counting but other behaviors are possible.

No comments: