问题
http://cplusplus.com/reference/string/basic_string/operator[]
I understand that it's advantageous to have a second version which returns const
to prevent warnings when a const
result is required and to mitigate casting but if the function already provides a non-const
method (method-- not result) then what is the point of declaring the const
-result method const
?
回答1:
You need to understand, that the second (const
) version not only returns a different result but is also marked itself as const
(this is the second const
at the end of the declaration):
const_reference operator[] (size_type pos) const;
These are two different things: The const
return value by itself would not be needed in the presence of a non-const
method (since the non-const return value can always be casted tò the const
version).
But not having a const
-version of the operator would mean, that you couldn't use it on const
string objects.
The const
result is just a result of the const
ness of the operator itself: if you have a const
string and use the operator to get a reference to a single character, clearly this reference must also be const
(if not, you could change single characters within a const
string).
回答2:
Assume you have
const std::string str{"test"};
std::cout << str[2];
If you don't have a const
member function, the code above will fail, as the this
pointer passed implicitly to operator[]
is const
.
回答3:
If you have a const std::basic_string
you cannot call (non-const) std::basic_string::operator[]
, as it is, well, not marked const.
回答4:
If there wasn't a const
version of the function, the function could not be invoked on a const
instance. For example:
void func (const std::string &h)
{
if (h[0] == "hello")
...
}
How would this work if there wasn't a const
version of operator[]
?
回答5:
The const
method returns a different type, it returns a const
-qualified reference. This means if the const
method is used, the result of the method is const
-qualified (and therefore is “immutable”). The non-const
-qualified method returns a regular reference, which is “mutable”.
You can't have just the const
method or else you can't modify individual characters in non-const
-qualified std::basic_string
objects. And you can't have just the non-const
method or you won't be able to call the method on const
-qualifed std::basic_string
objects.
来源:https://stackoverflow.com/questions/34983475/why-is-stdbasic-stringoperator-a-const-method-if-its-also-a-non-const-met