From: Daniel Krügler on
On 7 Jul., 04:20, Brendan <catph...(a)catphive.net> wrote:
> With std::strings I've always been leery of doing the same thing since
> I know that some std::string implementations, gcc's in particular, are
> Copy On Write. To make this safe, a COW string str would have to make
> a copy when you do a str[index] if there is more than one reference to
> the underlying string. Does the standard require this to be safe?

Yes. The C++03 standard does handle this problem in two ways:

1) It defines restrictions in regard to invalidation of pointers,
references, and iterators as follows ([lib.basic.string]/5):

"References, pointers, and iterators referring to the elements
of a basic_string sequence may be invalidated by the following
uses of that basic_string object:
[..]
� Calling data() and c_str() member functions.
[..]"

This means that a user holding a *reference/iterator/pointer* to
a string character, is responsible to honor invalidations of this
particular string object (I left only the interesting ones above,
because they exist purely to support reference-counted
implementations).

2) The standard adds a note in p. 6 that gives a hint for
implementations, that basic use-cases should be possible:

"[Note: These rules are formulated to allow, but not require, a
reference
counted implementation. A reference counted implementation must have
the same semantics as a non-reference counted implementation.
[Example:
string s1("abc");
string::iterator i = s1.begin();
string s2 = s1;
*i = �a�; // Must modify only s1
�end example] �end note]"

I assume that your example was supposed to describe a similar
scenario as this example.

HTH & Greetings from Bremen,

Daniel Kr�gler


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

From: Mathias Gaunard on
On Jul 7, 3:20 am, Brendan <catph...(a)catphive.net> wrote:
> With vectors, you can take the address of the first element in order
> to pass the underlying data to API's that take char*'s like so:
>
> vector<char> v(BUF_SIZE);
> // for some function: void write_to_buf(char* buf, size_t buf_len)
> write_to_buf(&v[0], BUF_SIZE);
>
> With std::strings I've always been leery of doing the same thing since
> I know that some std::string implementations, gcc's in particular, are
> Copy On Write.

More importantly, strings are not even guaranteed to be stored
contiguously...

> To make this safe, a COW string str would have to make
> a copy when you do a str[index] if there is more than one reference to
> the underlying string.

If your string is not a copy of any other string, then it should work.


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]