This is the mail archive of the
gcc-bugs@gcc.gnu.org
mailing list for the GCC project.
Pb with <string>
- To: egcs-bugs at cygnus dot com
- Subject: Pb with <string>
- From: ebert at pe-muc dot de (R. Ebert)
- Date: 17 Dec 1997 18:00:29 +0100
- Reply-To: egcs-bugs at cygnus dot com
There is a bug in <string> as objects initialized from another string do
not necessarily get their own copy.
-----------------------------------
#include <string>
int
main ()
{
string s1 = "abc";
char& rc = s1[1]; // 'b'
string s2 = s1; // totally independ object that happens to be initialized
// from another string object
cout << "s2 (expected: |abc|) " << s2.c_str() << endl; // ==> "abc"
rc = 'X';
cout << "s2 (expected: |abc|) " << s2.c_str() << endl; // ==> "aXc" !!!!
}
-----------------------------------
same bug reproduced in another form which happens more likely:
-----------------------------------
void f(const string& s, char& c)
{
string s3 = s;
cout << "s3 (expected: |abc|) " << s3.c_str() << endl; // ==> "abc"
c = 'Y';
cout << "s3 (expected: |abc|) " << s3.c_str() << endl; // ==> "aYc"
}
int main ()
{
// string - BUG 1 - Demo 2
string s1 = "abc";
f(s1,s1[1]);
}
-----------------------------------
The cure is in bastring.h implementation of operator[]:
reference operator[] (size_type pos)
{ unique (); return (*rep ())[pos]; }
^^^^^^
unique() is not enough, selfish() must be called.
Rolf
ebert@pe-muc.de