|
Boost Users : |
From: Lynn Allan (l_d_allan_at_[hidden])
Date: 2006-04-08 12:42:10
> On 4/8/06, Lynn Allan <l_d_allan_at_[hidden]> wrote:
>>
>> Sorry if this is off-topic.
>>
>> Just wanted to check .... are std::string's defined to be null
>> terminated?
>>
>> I came across a web page that indicated they are, but you can find lots
>> of
>> misinformation on the web.
>> http://www.codeproject.com/string/cppstringguide2.asp
>>
>> std::string's seem to be null terminated with the Microsoft vc7.1 and vc8
>> compiler, but I wanted to check if this is generally true according to
>> the
>> C++ standard.
>>
>> I'm relatively new to stl and using std::string .... mostly have used C
>> strings and MFC CStrings (which changed from vc6 to vc7.1?)
>
From: "Olaf van der Spek" <olafvdspek_at_[hidden]>
> std::string::c_str() returns a pointer to a null-terminated string, yes.
Thanks, but that isn't quite my question. I'm interested in the actual
internal layout of the data in the actual std::string.
I realize that myString.c_str() returns a null terminated string, but my
understanding is that the result of c_str() can be a separate buffer, not
necessarily a pointer to the buffer used by the std::string. Does the
internal data structure of the std::string itself have null termination, by
definition of the C++ standard?
I looked a little harder, and the vc7.1 and vc8 documentation for
std::string.c_str() states:
Objects of type string belonging to the C++ template class
basic_string<char> are not necessarily null terminated. The null character '
\0 ' is used as a special character in a C-string to mark the end of the
string but has not special meaning in an object of type string and may be a
part of the string just like any other character. There is an automatic
conversion from const char* into strings, but the string class does not
provide for automatic conversions from C-style strings to objects of type
basic_string<char>.
But it seems like the vc7.1 implementation of c_str provides the actual
address of the internal buffer:
std::string strC("HIJKL");
pTest = strC.c_str();
for (int i = 0; i < 80; ++i) {
printf("I: %2d Address: %d ch:%3d %c\n", i, &pTest[i], pTest[i], pTest[i]);
}
printf("\n********************\n");
printf("Sizeof std::stringC: %d\n", sizeof(strC));
printf("&strC: %d\n", &strC);
printf("strC.c_str(): %d\n", strC.c_str());
printf("(const char*)strC.c_str(): %d\n", (const char*)strC.c_str());
char* pNonConst = (char*)pTest;
pNonConst[3] = 'X';
printf("%s %s %s\n", strC.c_str(), pTest, pNonConst);
results in:
HIJXL HIJXL HIJXL
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net