Re: why does this call the destructor?
On Fri, 04 May 2007 08:14:57 +0200, michael <spam@begone.net> wrote:
Hi All,
I have written the following to illustrate a problem.
I know I have some magic numbers etc please ignore them.
What I do not follow is why the line marked results in a call to the
destructor for the object.
Can someone please explain it for me?
#include <iostream>
#include <fstream>
using std::ostream;
class someClass {
private:
char *str;
public:
someClass();
~someClass();
friend ostream& operator <<(ostream& lhs, someClass rhs);
};
someClass::someClass(){
str = new char[10];
strcpy(str, "something");
}
someClass::~someClass(){
std::cout << "\nIn someClass destructor...\n";
delete str;
}
use delete[]
ostream& operator <<(ostream& lhs, someClass rhs){
lhs << rhs.str; // This results in a call to the destructor=
=
for
the someClass object....why?
return lhs;
}
The destructor is not called where you think it is, but when control =
reaches the end of the function. This is indeed the destructor of the =
copy, not of the original object. Your problem here however is that the=
=
destructor deletes the memory pointed to by str. This is *the same =
memory* as in the original object. To create the copy, the compiler had=
=
to create a copy constructor. However this copy constructor only copied=
=
the pointer, not its contents. Conceptually, this is the same as if you=
=
had written:
class someClass()
{
// same as what you wrote, but with this addition:
someClass( const someClass& rhs )
{
str = rhs.str; // only copies the pointer, not the memory it po=
ints =
to
}
};
Solve this by adding a copy constructor and assignment operator. And of=
=
course you should pass arguments by const reference here - although in =
this case that would have meant you wouldn't have found the problem with=
=
your code.
Ben
-- =
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/