写std :: string是合法的吗? [英] Is it legal to write to std::string?

查看:130
本文介绍了写std :: string是合法的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在std :: string中,只有const成员来获取像c_str()这样的数据。但是,我可以通过 operator [] 获得对字符串的第一个元素的引用,我可以写它。



例如,如果我有函数:

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

我可以直接写向vector获取指向第一个元素的指针:

 矢量< char> message //有Some Message; 
toupper(& message [0],& message [0] + message.size());

我可以用std :: string吗?

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

标准是否保证内存的位置实际上是线性的?即:

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

感谢。

解决方案>

std :: string将需要具有新的c ++ 0x标准的连续存储。目前是未定义的行为。


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.

解决方案

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

这篇关于写std :: string是合法的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆