Pb with <string>

R. Ebert ebert@pe-muc.de
Wed Dec 17 08:52:00 GMT 1997


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



More information about the Gcc-bugs mailing list