开发者

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜