| MasterAsh (29) | |||
|
Hi guys! consider:
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. | |||
|
|
|||
| Disch (8621) | |
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.
| |
|
|
|
| Peter87 (3917) | |
| 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. | |
|
|
|
| MasterAsh (29) | |||
|
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:
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
|
|||
| Peter87 (3917) | |
Is m_str a member of S? In that case line 8 should be cout<<obj1.m_str;
| |
|
|
|
| MasterAsh (29) | |
| yeah right...i'm sorry.i'll edit this right now.done. | |
|
Last edited on
|
|
| Peter87 (3917) | |
| Maybe there is a bug in your copy constructor? | |
|
|
|
| Disch (8621) | |
|
+1 Peter. There must be a problem with the copy constructor. | |
|
|
|
| MasterAsh (29) | |
|
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
|
|