Fred Foo
Fred Foo

Reputation: 363737

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_casts 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).

  1. Was my first attempt with const_cast thread-safe?
  2. Is my new approach thread-safe, or should db also be marked volatile?

Upvotes: 3

Views: 1190

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126378

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.

Upvotes: 2

Related Questions