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 ?
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.
Make the lock mutable
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With