D
Dev
Hello,
In the following class definition,
the ZString destructor is invoked two times.
This crashes the code.
class ZString
{
public:
ZString(char* p)
: _sz:strlen(p)),
_p(new char[_sz+1])
{
::strcpy(_p,p);
}
~ZString()
{
delete [] _p;
}
char& operator [] (int i)
{
return _p;
}
private:
int _sz;
char* _p;
};
int main(int argc, char* argv[])
{
ZString s1("John");
ZString s2 = s1;
return 0;
}
An immediate solution that comes to my mind is to provide
the implementation of the assignment operator, wherein a
new ZString object is created using the field values from the
existing ZString object (rhs).
Can anybody suggest better approaches to improve the class
implementation, with trade offs ?
Thanks in advance.
Dev.
In the following class definition,
the ZString destructor is invoked two times.
This crashes the code.
class ZString
{
public:
ZString(char* p)
: _sz:strlen(p)),
_p(new char[_sz+1])
{
::strcpy(_p,p);
}
~ZString()
{
delete [] _p;
}
char& operator [] (int i)
{
return _p;
}
private:
int _sz;
char* _p;
};
int main(int argc, char* argv[])
{
ZString s1("John");
ZString s2 = s1;
return 0;
}
An immediate solution that comes to my mind is to provide
the implementation of the assignment operator, wherein a
new ZString object is created using the field values from the
existing ZString object (rhs).
Can anybody suggest better approaches to improve the class
implementation, with trade offs ?
Thanks in advance.
Dev.