Tutorial :Is it legal to write to std::string?



Question:

In std::string there are only const members to fetch the data like c_str(). However I can get a reference to the first element of the string via operator[] and I can write to it.

For example, if I have function:

void toupper(char *first,char *last_plus_one);  

I can write directly to vector getting a pointer to the first element:

vector<char> message // has "Some Message";  toupper(&message[0],&message[0]+message.size());  

Can I do same thing with std::string?

string message="Some Message";  toupper(&message[0],&message[0]+message.size());  

Does the standard guarantee that the location of the memory is actually linear? ie:

&(*(message.begin()+n)) == &message[n]  

Thanks.


Solution:1

std::string will be required to have contiguous storage with the new c++0x standard. Currently that is undefined behavior.


Solution:2

Herb Sutter has this to say (http://herbsutter.wordpress.com/2008/04/07/cringe-not-vectors-are-guaranteed-to-be-contiguous/#comment-483):

current ISO C++ does require &str[0] to cough up a pointer to contiguous string data (but not necessarily null-terminated!), so there wasn’t much leeway for implementers to have non-contiguous strings, anyway. For C++0x we have already adopted the guarantee that std::string contents must indeed be stored contiguously. For details, see http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#530

And Matt Austern says similar in the referenced document (http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#530).

So, it seems that you can assume that once you call str[0] you do get a modifyable array of characters (but note that it is not required to be null terminated).


Solution:3

Yes you can modify a string.

You can also use it in algorithms that use iterators.

You can not use it in the same way as a vector<> because there is no guarantee that elements are in contiguous memory locations (yet: coming to a standard near you soon).

So if you modify your approach to use iterators rather than pointers it should work. And because iterators behave very much like pointers the code changes should be negligible.

template<typename I>  void toupper(I first,I last_plus_one)  {      // Probably the same code as you had before.  }      {       std::string  s("A long string With Camel Case");         toupper(s.begin(),s.end());  }  


Solution:4

As it has been pointed-out, one can use strings in algorithms that use iterators; the same case can be implemented using std::transform Ex:- consider a string 's' to be converted to lower case:

int (*pf)(int)=tolower; //lowercase  std::transform(s.begin(), s.end(), s.begin(), pf);   

Regards,


Solution:5

I think that it gives you an undefined behavior. Use a stringstream to write to, and then use the str() member to get the string of the stream.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »