#21 Support for logical constness

open
nobody
5
2006-08-14
2006-08-13
Markus Elfring
No

Would you like to add support for the C++ key word
"mutable"?
http://jamesthornton.com/eckel/TICPP-2nd-ed-Vol-one/Chapter08.html#Index1583

Example:
A function signature like "int
worker_fifo::get_nthreads() const" would become useable
again.
http://felix.cvs.sourceforge.net/felix/lpsrc/flx_pthread.pak?view=diff&r1=text&tr1=1.41&r2=text&tr2=1.40&diff_format=h

Discussion

  • John Skaller
    John Skaller
    2006-08-13

    Logged In: YES
    user_id=5394

    I'm not sure what you mean by 'adding support'. Do you mean,
    you think it would have been better to use a mutable member
    in this instance?

    I thought of that briefly, but in the end decided to just
    chuck out the 'const', since I have learned over the years
    that C++ gets it wrong a lot.

    In this case, it isn't even clear get_nthreads() really is
    logically const.

    In fact .. it isn't clear why nthreads needs to be protected
    by a mutex. That assumes someone other than the owner thread
    can change the number of threads in the job pool ..and that
    doesn't make sense: there could be contention. Serialising
    the thread count will not resolve the contention. In fact
    the 'set_nthreads()' function will fail if two threads both
    call it.

    So actually, your original suggestion is probably wrong:
    nthreads doesn't need protection, it is set_nthreads() that
    needs protection: it needs to be available only to the
    owner, and in that case access will be serial anyhow and
    doesn't require serialisation by a mutex :)

    The only way to enforce this would be to store the current
    thread ID and check it on entry to that function (and others
    that modify it).

     
  • Markus Elfring
    Markus Elfring
    2006-08-14

    • summary: Supprt for logical constness --> Support for logical constness
     
  • Markus Elfring
    Markus Elfring
    2006-08-14

    Logged In: YES
    user_id=572001

    Yes, a mutable member is better - I know a few use cases
    that are more appropriate than the current example.

    More explanations are in the answer for the question 'What
    do I do if I want a const member function to make an
    "invisible" change to a data member?'
    http://www.dietmar-kuehl.de/mirror/c++-faq/const-correctness.html#faq-18.13

    Please keep in mind:
    Each attribute that can be changed by multiple threads must
    be protected with mutual exclusion für write and read access.
    A mutex does all synchronisation you need for you. Don't
    think about to fiddle with thread IDs.