Is relying on the const-ness of arguments bind to const& parameters a recipe for thread un-safety?

35 Views Asked by At

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?

1

There are 1 best solutions below

0
Sam Varshavchik On

No, nobody could possibly tell you that. This is a common misunderstanding of what a const object means.

A const object is not a promise that some other execution thread can't modify the object, while you go about your business.

A const object is a promise that the code that accesses the const object cannot modify it (whatever "modify" means for the object in question).

In fact, no other execution thread needs to be involved, at all. This foo function, in the "stuff" part, can call some other function that has access, via some pointer or reference somewhere, the exact same const object and completely change it inside and out, then return to this foo function.