a very quick question about "this"

Hi guys!
consider:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class S
{public:
  
   S(S&);
   void operator= (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.
Last edited on
Is m_str a member of S? In that case line 8 should be cout<<obj1.m_str;
yeah right...i'm sorry.i'll edit this right now.done.
Last edited on
Maybe there is a bug in your copy constructor?
+1 Peter.

There must be a problem with the copy constructor.
aw sorry,you were totally right,it was the copy constructor,turns out i hadn't written it the way i thought
i had...thanks a lot.
Last edited on
Topic archived. No new replies allowed.