class S
{public:
S(S&);
voidoperator= (S&);
~S();
S& W()
{
//some code
return *this;
}
};
i noticed(by accident) that if the ampersand in the declaration of W()
is omited,then ~S() is called each time W() returns.
why does that happen?
sorry if it's a dumb question and thanks in advance.
S W() { return *this; } Returns a COPY of this, which is destroyed after it is used (hence why the destructor is being called -- the copy is being destroyed when it's no longer needed).
S& W() { return *this; } Returns a REFERNECE to this. There is no copy.
The ampersand means it is a reference. W() is returning a reference the object. If you remove the ampersand it will return a copy of the object and it is probably that object's destructor you see being called.
thanks guys,but i guess i didn't ask my question clearly enough.i know that
the & is a reference,and i'm aware that S W() {return * this;} returns a copy of this,
i've already overloaded the default copy constructor and the = operator in order to prevent shallow copies.
now the destrucor that is called is NOT the destructor of the copy of this,it's the destructor of this.
because:
1 2 3 4 5 6 7 8 9
//assume that S has a member declared as char* m_str,initialized somewhere before using W()
//for example let's say m_str=="cool";
//also assume S W() as the declaration of W
//by the way m_str is deleted in ~S()
S obj1;
obj1.W();
cout<<obj1.m_str;//now it's just garbage,not "cool" anymore
so if only the destructor of the copy was called(and shallow copies were prevented with a copy constructor)
then why would m_str be deleted?
so that was the problem:why is the destructor of this called,instead of only the destructor of the copy?
thanks for your patience.