0
string& operator+= (const string& str);

When we look at the function prototype, we assume that the string passed into the function won't be changed, right?

However, consider the situation:

string str("Example");
str += str;

The string 'str' was changed, actually. Isn't this kind of scenario considered strange?

Will it be better to change the prototype to?

string& operator+= (string& str);

I have searched lots of sources and examples like this, but it seems normal to most people. There's no one asking about it, or it might be the case that I didn't find one.(Sorry if it's my problem, it's so hard to find the proper keywords for non-native speaker)

1 Answers1

0

const does not say that a function parameter cannot be modified at all. It simply says that it cannot be modified through that parameter. If you pass a particular object as both a const and a non-const argument then you can hardly act surprised if it changes!

On the other hand, if you declare the object itself const, then you can guarantee (more or less) that it isn't changed at all, since attempting to pass it as a non-const parameter will just fail.

nneonneo
  • 171,345
  • 36
  • 312
  • 383