You are right, a copy will be made in all four examples (L1, L2 and two below), although this is not necessary for the last two.
Unfortunately, when the non-constant version of the operator [] is called or the non-constant iterator is dereferenced, there is no way for the implementation to determine whether the resulting non-constant link will be used to modify the object, so it must be safe and make a copy.
C ++ 11 added the functions cbegin() and cend() to strings and other containers that return constant iterators, even if called in a non-constant object. This helps fix the problem. I do not know a comparable solution for the [] operator.
Note: the presence of the operator [] or the iterator operator * () returns the type of proxy server, as suggested by some other respondents, as this violates the requirements of the container, one of which is that these functions return valid links, (That's why everyone agrees so that vector<bool> is a mistake - it uses proxies in this way).
(Of course, if you write your own class with reference counting, then this does not stop you from using proxy types.)
Highcommander4
source share