Prev: compilation error when Base Constructor calling pure virtual method
Next: will taking the address of the first element of a string break COW strings?
From: Seungbeom Kim on 6 Jul 2010 21:08 On 2010-07-06 19:20, Brendan 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. 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? I don't think you are allowed to pass the internal buffer of a std:: basic_string and have it modified, even without reference-counting. 21.3.4: const_reference operator[](size_type pos) const; reference operator[](size_type pos); Returns: if pos < size(), returns data()[pos]. Otherwise, if pos == size(), the const version returns charT(). Otherwise, the behavior is undefined. 21.3.6: const charT* data() const; Returns: if size() is nonzero, the member returns a pointer to the initial element of an array whose first size() elements equal the corresponding elements of the string controlled by *this. If size() is zero, the member returns a non-null pointer that is copyable and can have zero added to it. Requires: The program shall not alter any of the values stored in the character array. Nor shall the program treat the returned value as a valid pointer value after any subsequent call to a non-const member function of basic_string that designates the same object as this. Therefore, it is clear that std::basic_string only gives you a read- only view of the string value, and it doesn't even guarantee that the array pointed to by data() is the same array as the "original" string; it is allowed to return a copy. In summary, std::basic_string claims exclusive access rights to its internals. If you want a direct access to the internals, you should use std::vector instead. -- Seungbeom Kim [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] |