Maybe dumb question regarding StringRef


#1

where the "const String&" function arguments have been converted to "StringRef"s, why has this been done dropping the "const"?

Is using a "const StringRef" conceptually wrong?


#2

You could use a const StringRef&, but the StringRef only contains a pointer, so passing it by value is more efficient (and easier for the compiler to optimise) than passing a pointer to it. See my comments about pass-by-value at the bottom of my coding standards page.


#3

Yes, I know those coding standards by heart by now :) (btw, the URL you linked doesn't link correctly, but I know what page you meant ;)) and I agree with them all.. my question was not about whether to use references or pass-by-value, I know it's more efficient to pass it by value in this case.

I was referring to the fact that using the StringRef the "const-ness" of the string data stops being enforced, and one could easily change the content of the original String by acting on the characters pointed by the public pointer that's member of StringRef. This is something that was not possible (unless with an explicit const_cast) when the "const String&" was used.

What do you think about making the "text" member private or const, so that the old behaviour is restored?


#4

You could make it const, I guess - it wouldn't do any harm! The text member does need to be accessible though, since that's how you actually use the string, and I made it public because the alternative of using a cast or accessor method seemed a bit cumbersome. The text member couldn't be const though, because that'd prevent the StringRef from having an operator=