关于AnsiString的读时共享,写时复制问题
AnsiString s1,s2;
s1 ="good";
s2 = s1;
char *ptr =s1.c_str();
s2 ="morning";
s1 = "help";
>>>>>>>>>输出结果>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
s1 = "help";
s2 = "morning";
*(ptr) = "s";
为什么*(ptr)='s'呢,不应该是"g"么
[解决办法]
char *ptr =s1.c_str();
这样写是错误的c_str()必须直接使用,不能二次赋值
[解决办法]
C++Builder帮助中的解释,说的很明白了。
AnsiString::c_str() returns a non const temporary pointer to the internal string buffer in the AnsiString object. The pointer is invalid once the statement in which it is used has finished executing. That is,don't do something like this:
char* cp = Edit1->Text.c_str();
char* cp2 = strtok( cp, " \t\n" ); // cp may no longer be valid
If you need a persistent pointer, you MUST copy the string into its own buffer:
char* cp = new char[ Edit1->Text.Length() + 1 ];
strcpy( cp, Edit1->Text.c_str() );