I just listened to this talk about how const
actually means bitwise immutable OR thread safe in and after c++11. Furthermore we should guarantee const functions to be thread safe. This is all well and good until I tried to implement it. Look at this example:
class Foo {
public:
void increment() const {
std::lock_guard<std::mutex> lk(m);
hiddenVal+=1;
}
private:
std::mutex m;
int hiddenVal=0;
};
This code is actually not going to compile because we are modifying the member variables even though the function is thread safe. So in the end to make the function actually valid we must declare the variables like this:
mutable std::mutex m;
mutable int hiddenVal=0;
Now I agree that mutex
is inherently thread safe so it makes sense for it to be mutable
but hiddenVal
is in no way thread safe so why are we forced to also make it mutable
? Now imagine this on a larger scale. Every function called from a const
function must also be const
. Every variable modified in const
functions must be mutable
. This honestly seems like an anti-pattern.
Aucun commentaire:
Enregistrer un commentaire