std :: string :: operator []的结果的地址是否指向可写的,nul终止的缓冲区? [英] Does the address of the result of std::string::operator[] point to a writable, nul-terminated buffer?
问题描述
我修改一个函数接受一个const char *并使用一个函数,ProcessString。 ProcessString是一个函数,期望一个以空字符结尾的字符缓冲区作为char *。缓冲区中的字符可以修改也可以不修改,如下面的函数签名所定义。为了弥合差距,我使用了一个临时的std :: string:
I am modifying a function that accepts a const char* and uses a function, ProcessString. ProcessString is a function that expects a null-terminated character buffer as a char*. The characters in the buffer may or may not be modified, as defined by the function signature below. To "bridge the gap", I am using a temporary std::string:
void ProcessString( char* str );
void SomeFunction( const char* str )
{
string temp(str);
ProcessString( &temp[0] );
}
$ b $ p我的主要问题是关于std :: string :: operator的保证[ ]以及由上面的& temp [0]返回的地址是否是可用的空终止缓冲区作为char *。
My primary question is about the guarantees of std::string::operator[] and whether the address returned by the &temp[0] above is a usable, null-terminated buffer as a char*. Secondly, and very much secondly, is there a better way to do this?
我使用C ++ 03。
I am using C++03.
推荐答案
在C ++ 11中只有明确定义的行为;在以前的标准中, std :: string
不保证其内部缓冲区的连续存储。
That only has well-defined behavior in C++11; in previous standards, std::string
did not guarantee contiguous storage for its internal buffer.
在C ++ 11中完全正常,更惯用的方法是使用 std:vector< char>
,它从C ++ 03开始保证连续存储:
However while that code is completely fine in C++11, the more idiomatic approach is to use std:vector<char>
, which has guaranteed contiguous storage since C++03:
void ProcessString(char* str);
void SomeFunction(char const* str)
{
// + 1 for terminating NUL
std::vector<char> temp(str, str + std::strlen(str) + 1);
ProcessString(&temp[0]); // or temp.data() in C++11
}
这篇关于std :: string :: operator []的结果的地址是否指向可写的,nul终止的缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!