GotW #6b Solution: Const-Correctness, Part 2 -- Herb Sutter

The solution to GotW #6b is now available:

GotW #6b Solution: Const-Correctness, Part 2 (updated for C ++11/14)

by Herb Sutter

From the article:

Option 1 is to use a mutex in the perhaps-soon-to-be-canonical “mutable mutex mutables” pattern:

// Option 1: Use a mutex

    double get_area() const {
        auto lock = unique_lock<mutex>{mutables};
        if( area < 0 )   // if not yet calculated and cached
            calc_area();     // calculate now
        return area;

    // ...
    mutable mutex  mutables;      // canonical pattern: mutex that
    mutable double area;          //   covers all mutable members

Option 1 generalizes well if you add more data members in the future. However, it’s also more invasive and generalizes less well if you add more const member functions in the future that use area, because they will all have to remember to acquire a lock on the mutex before using area.

Option 2 is to just change double to mutable atomic<double>. ...


Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.