Is it legal to write to std::string?

2019-01-15 12:36发布

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.

5条回答
再贱就再见
2楼-- · 2019-01-15 13:09

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

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-15 13:16

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

查看更多
我想做一个坏孩纸
4楼-- · 2019-01-15 13:20

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.

查看更多
在下西门庆
5楼-- · 2019-01-15 13:22

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,

查看更多
男人必须洒脱
6楼-- · 2019-01-15 13:28

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());
}
查看更多
登录 后发表回答