Iterators and Reference Counted Strings

If we look at an implementation of std :: string that uses reference counting, consider this scenario:

int main() { string english = "Hello"; string german = english; //refcnt = 2 string german2 = german; /* L1 */ german[1] = 'a'; /* L2 */ *(german2.begin() + 1) = 'A'; cout << english << endl << german << endl << german2 << endl; return 0; } 

What happens in L1 and L2? Is link counting and deep copying done? I think so, but my concern is that if this happens, make it simple:

 cout << german[1] << endl; 

or simply:

 cout << *(german.begin()) << endl; 

in non-constant contexts, unnecessary deep copies will be executed. I'm right? How do implementations deal with this detail?

+7
source share
2 answers

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.)

+6
source

One way to achieve this is through proxy classes. Therefore, when you index a string, and if you get a char, you get an object that looks and looks like a char. When recording is performed on it, it invokes a deep copy of the original string.

+2
source

All Articles