[Click] Can't use String::c_str on const String

Eddie Kohler kohler at icir.org
Tue Oct 14 11:41:15 EDT 2003


> i wonder if it's okay to have benevolent side effects on a C++ `const' 
> object?
> according to 6.170 gospel, it should be cool, but you could imagine 
> problems with friend classes/methods making strong assumptions about 
> constness.

Well, I think it's generally cool, as long as the abstract representation
doesn't change. (And String has no real friends.) It's a bit weird with
String, though, since the "const char *data() const" pointer is part of the
abstract rep, and "c_str()" might change the "data" pointer.

But the more I think about it, the more I think it's probably OK.

We should not change c_str() to const if there is some code:
1. That people want to write,
2. That would not compile before the change,
3. That would compile after the change, and
4. That is erroneous.

Here's the best example I can come up with:

  void foo(const String &s, ErrorHandler *errh) {
    const char *d = s.data();
    for (int i = 0; i < s.length(); i++, d++) {
      if (d[i] == WHATEVER)
        errh->error("Sucky string, continuing %s", s.c_str());
				      // should be String(s).c_str()
  }

This seems a little obscure.

An interesting non-example: Sharing a "const String &s" among concurrently
executing threads -- Calling s.c_str() will not be more of a problem than
calling "String(s).c_str()"; the first modifies "s", the second modifies
"s"'s shared Memo object.

So, I think I'll check in this change.
Eddie


More information about the click mailing list