清风竹林

ぷ雪飘绛梅映残红
   ぷ花舞霜飞映苍松
     ----- Do more,suffer less

std::string is contiguous (转)

原文地址: http://hpyblg.wordpress.com/2010/06/03/stdstring-is-contiguous/

You can safely assume that the memory buffer used by std::string is contiguous. Specifically, the address of the string’s first character can be used as the address for the whole string, just like a C-style char array:

1std::string str = "foo";
2strncpy(&str[0], "bar", 3); // str now contains "bar".

Why is this safe? The current C++ standard apparently doesn’t guarantee that the string is stored contiguously, but it is in all known implementations. Additionally, the next C++ standard (C++0x) will make this guarantee. So the above usage is valid on all present and future C++ implementations.

Why is this important? It’s common for functions, especially in the Windows API, to “return” strings by copying them into a buffer passed to the function. Since the memory buffer used in std::string is contiguous you can safely pass it to the function, after resizing the string to the correct size.

A typical usage for Windows API functions:

01// get required buffer size
02DWORD bufSize = 0;
03GetComputerNameA(NULL, &bufSize);
04if (!bufSize && GetLastError() != ERROR_BUFFER_OVERFLOW) {
05  throw std::runtime_error("GetComputerNameA failed");
06}
07// bufSize now contains required size of buffer, including null terminator
08std::string buf(bufSize, '\0');
09if (!GetComputerNameA(&buf[0], &bufSize)) {
10  throw std::runtime_error("GetComputerNameA failed");
11}
12// bufSize now contains actual size of data
13buf.resize(bufSize);
14// now use buf as a regular std::string

This is cumbersome but actually easier than plain C code, since you don’t have to manage the memory yourself.

Note that the expression &str[0] is valid only if str isn’t empty. Also, everything I’ve said also applies to std::wstring, the wide-character version of std::string.

References:

posted on 2011-05-26 20:52 李现民 阅读(538) 评论(3)  编辑 收藏 引用 所属分类: 绝对盗版

评论

# re: std::string is contiguous (转) 2011-05-27 10:35 oldman

为什么不用 str.data() 呢?  回复  更多评论   

# re: std::string is contiguous (转) 2011-05-27 10:45 李现民

@oldman
&str[0]的数据是可以修改的, 而str.data()的数据不能修改  回复  更多评论   

# re: std::string is contiguous (转) 2011-05-27 10:50 oldman

哦,明白你的意思了。我的意思是说既然现在大家对于data的实现也是直接拿内部数据返回的,拿出来去掉const属性,一样可以用。  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理