Dev wrote:
Dev wrote:
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);
}
I added an copy constructor here.
int main(int argc, char* argv[])
{
ZString s1("John");
ZString s2 = s1;
return 0;
}
Additionally, I set s1 = 0
immediately after construction of s2.
Now, I get a Segmentation Fault.
Is there a way to get around this problem ?
Of course, what sort of language do you think C++ is?
You should stop focussing on the two calls to the destructor, that is
correct, it is what happens before that that is incorrect. Since you
haven't posted the copy constructor you wrote I would expect that the
error is there.
You are also missing an operator= for you class, which is essential in
the long run, but should not be causeing the problems above. It's a
common situation in C++ that when yu program crashes, it not the code at
the point it crashes that is wrong but the code somwhere before where it
crashes.
I don't understand what you mean by 'Additionally, I set s1 = 0' does
that mean that you program was literally like this
int main(int argc, char* argv[])
{
ZString s1("John");
ZString s2 = s1;
s1 = 0;
return 0;
}
If that is the case, then I don't understand why you are surprised you
got a crash. It's an obvious null pointer error.
Here is a working ZString class and program. The main changes from you
code are the addition of const in the appropriate places, a working
assignment operator and copy constructor and a const version of
operator[]. All these things are necessary for a simple string class.
#include <cstring>
#include <algorithm>
class ZString
{
public:
ZString(const char* p)
: _sz(::strlen(p)),
_p(new char[_sz+1])
{
::strcpy(_p,p);
}
ZString(const ZString& rhs)
: _sz(::strlen(rhs._p)),
_p(new char[_sz+1])
{
::strcpy(_p, rhs._p);
}
void swap(ZString& rhs)
{
std::swap(_sz, rhs._sz);
std::swap(_p, rhs._p);
}
ZString& operator=(const ZString& rhs)
{
ZString tmp(rhs);
swap(tmp);
return *this;
}
~ZString()
{
delete [] _p;
}
char& operator [] (int i)
{
return _p[i];
}
char operator [] (int i) const
{
return _p[i];
}
private:
int _sz;
char* _p;
};
int main(int argc, char* argv[])
{
ZString s1("John");
ZString s2 = s1;
return 0;
}
john