c++ - Overwriting custom string failing when non-default ctor was explicitly called -
for exercise in accelerated c++ i'm implementing custom string class called str
. worked fine when underlying storage container custom vector (vec
) i've run weird situational problem don't understand.
if create new str
object explicitly calling constructor str newstr("some words");
, try overwrite using cin >> newstr;
program crashes in end, giving sigabrt in debugger when reaches str
destructor (which delete[] data;
).
this doesn't happen if create new, empty str
use cin
fill str newstr; cin >> newstr;
, or if use cin
overwrite str
made using str newstr = "some words";
, fails when attempt overwrite str
made explicitly calling non-default constructor though type displays correctly before being overwritten.
another weird thing in case works fine if don't create new str
s between creating/displaying odd-behavior str
, using cin
change value.
str = "here a"; str b("and here b"); cout << << endl << b << endl; str c = "finally have c"; cout << c << endl; cin >> c; cout << c << endl << endl; cin >> b; cout << b << endl;
this shows you can overwrite str c
successfully, crashes when try overwrite str b
. this, however, lets overwrite b
, program completes successfully:
str = "here a"; str b("and here b"); cout << << endl << b << endl; cin >> b; cout << b << endl;
str
contains private members char* data
, int length, limit
, constructor being used both a
, b
is:
str::str(const char* cp) { limit = length = std::strlen(cp); data = new char[length]; (size_type = 0; != length; ++i) data[i] = cp[i]; }
i have >>
friended , implementation is:
istream& operator>>(istream& is, str& s) { delete[] s.data; s.length = s.limit = 0; char c; while (is.get(c) && isspace(c)) ; if (is) { s.push_back(c); while (is.get(c) && !isspace(c)); if (is) is.unget(); } return is; }
i know push_back
might odd function have in class works fine when using cin
long str
takes many push_backs. i've tried tweaking different parts of class/operators hours , stumped o_o
lastly, i'm not sure why copy ctor isn't being called (checked cout
s) during str
initialization uses str newstr = "blah";
syntax, though works.
edit, push_back:
void str::push_back(char c) { if (length == limit) { limit = std::max(limit*2, 1); char* newdata = new char[limit]; (size_type = 0; < length; ++i) newdata[i] = data[i]; delete[] data; data = newdata; } data[length++] = c; }
when delete[]
ing memory in input operator, need make sure data
member set 0
. if don't that, you'll delete[]
non-null pointer delete[]
d in push_back()
, program have undefined behavior:
istream& operator>>(istream& is, str& s) { delete[] s.data; s.data = 0; // needed keep class invariants correct s.length = s.limit = 0; // ... }
Comments
Post a Comment