I was just saw code like this
/* whatever */ foo(std::string const& s) {
// stuff
auto L = s.length();
int i{/* init based on L */};
while (i < L) {
// do other stuff and maybe
++i;
}
}
and I was going to suggest that one can avoid defining L and write
/* init based on s.length() */ and (i < s.length()) instead of /* init based on L */ and (i < L).
But who's really telling me that s.length() doesn't change unpredictably because the argument corresponding to the s parameter is changed by another concurrent thread?
No, nobody could possibly tell you that. This is a common misunderstanding of what a
constobject means.A
constobject is not a promise that some other execution thread can't modify the object, while you go about your business.A
constobject is a promise that the code that accesses theconstobject cannot modify it (whatever "modify" means for the object in question).In fact, no other execution thread needs to be involved, at all. This
foofunction, in the "stuff" part, can call some other function that has access, via some pointer or reference somewhere, the exact sameconstobject and completely change it inside and out, then return to thisfoofunction.