Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const cast to allow read lock, does this smell bad?

I want to execute a read-only method on an object marked as const, but in order to do this thread-safely, I need to lock a readers-writer mutex:

const Value Object::list() const {
  ScopedRead lock(children_);
  ...
}

But this breaks because the compiler complains about "children_" being const and such. I went up to the ScopedRead class and up to the RWMutex class (which children_ is a sub-class) to allow read_lock on a const object, but I have to write this:

inline void read_lock() const {
  pthread_rwlock_rdlock(const_cast<pthread_rwlock_t*>(&rwlock_));
}

I have always learned that const_cast is a code smell. Any way to avoid this ?

like image 447
Anna B Avatar asked Jan 28 '10 19:01

Anna B


2 Answers

Make the lock mutable

mutable pthread_rwlock_t rwlock;

This is a common scenario in which mutable is used. A read-only query of an object is (as the name implies) an operation that should not require non-const access. Mutable is considered good practice when you want to be able to modify parts of an object that aren't visible or have observable side-effects to the object. Your lock is used to ensure sequential access to the object's data, and changing it doesn't effect the data contained within the object nor have observable side-effects to later calls so it is still honoring the const-ness of the object.

like image 94
RC. Avatar answered Oct 21 '22 01:10

RC.


Make the lock mutable.

like image 22
James McNellis Avatar answered Oct 21 '22 01:10

James McNellis