mutable keyword and thread-safety
I have an abstract base class
class Map {
public:
virtual Value get(Key const &) const;
};
a database class from an external library
class Database {
public:
// logically const and thread-safe
Value get(Key const &key);
};
and I started with an implementation like
class PersistentMap : public Map {
Database db;
public:
Value get(Key const &key) const
{ return const_cast<Database &>开发者_开发百科;(db).get(key); }
};
As the number of const_cast
s grew beyond bounds, I got rid of them by adding a mutable
specifier to PersistentMap::db
(and a comment to remind myself of its ugliness).
- Was my first attempt with
const_cast
thread-safe? - Is my new approach thread-safe, or should
db
also be markedvolatile
?
It depends entirely on whether Database::get is thread-safe or not. If it contains locks to prevent concurrent access, or is otherwise safe for concurrent access, then your code is fine with either the const_cast or the mutable. Using volatile is completely irrelevant.
精彩评论