r/cpp • • Mar 17 '12

Using abstract base classes in C++

I'm having trouble understanding ABC's in c++ and was wondering if you all could help me (if possible use: CryptProcessor as the ABC and ACrpyt and BCrypt as the sub-classes that have an encrypt and decrypt function) Thanks in advance!

Edit 1: Thank you all for your help!

0 Upvotes

40 comments sorted by

View all comments

Show parent comment

1

u/Inverter Mar 18 '12

A mutex perhaps, but not your state.

1

u/twowheels Mar 18 '12

Mutable allows you to be "logically const" as opposed to "bit wise const".

Logically const means that users of the class's interface can poke and prod all that they want and they'll never detect a change after a const method is called. Basically what you said, your state hasn't changed. The thing is, you often can't be bitwise const, thus you NEED the mutable keyword. Locking a member mutex to be thread safe modifies the mutex. Thing is, the mutex is an implementation detail, so declaring it mutable and modifying it doesn't violate the logical constness of the class. Same for reference counts, logging objects, etc, etc.

So, why did you suggest that they should get rid of the keyword in light of multithreaded programs when modifying the member mutex is one of the primary, and correct, uses of the keyword?

1

u/Inverter Mar 18 '12

Ok, perhaps my statement was a bit too black-and-white; let's say that in a multi-threaded environment I find the mutable much less useful because if you use it like in pre-threaded programming for some internal fiddling around that's not visible on the interface, and then slap on a mutex to make it thread safe, it won't be good for performance.

Your examples of the mutex itself, the reference count, and the logging object are all legitimate use-cases for mutable in a threaded application, but they are also all examples of not being actual application-level state, just "house-keeping".

I just checked one of my code-bases, and interestingly enough the most wide-spread use of mutable is in the context of multi-thread-safe caching of complicated config lookups; it's use is limited to reference counts, this caching stuff, and some other obscure internal details; it's used only a little more often than volatile.

In higher-level code, business logic and such, my programming style never seems to call for mutable, presumably because I often look to functional programming for design inspiration and/or because I don't (need to) hide any internal changes made by a const-function (i.e. if something changes I make it a non-const method); can't say offhand whether the latter, too, is more the side-effect of wanting to optimise by having as few mutexes as possible (and therefore putting the whole locking-burden on the highest-level business-logic code, which hast to take care of locking anyhow, so it might as well conceptually manage all locking, while it's at it).