0

What i think is occuring is that the rvalue A returned by SetVar is an identical copy to Class and shares the same pointer Var. but when the rvalue calls its deconstructor it deletes Class's Val.

class A
{
private:
    int* Var;
public:
    A SetVar(int);
    ~A()
    {
        delete Var;
    }
};

A A::SetVar(int NewVar)
{
    Var=new int;
    *Var=NewVar;
                //POINT A
    return *this;
}

int main()
{
    A Class;
    Class.SetVar(8);

                //POINT B
}

At POINT A *Val equals 8, but at POINT B *Val equals -17891602. I also Get _BLOCK_TYPE_IS_VALID(pHead->nHeadUse) due to trying to delete Val twice.

deleting the deconstructor solves the issue but creates a memory leak.

Lauer
  • 517
  • 1
  • 6
  • 11
  • How do you know the value? I have a feeling what you think was point 'B' is actually point 'C' the other side of the destructor. The value `-17891602` is a very suspicious looking `0xFEEEFEEE`. See: http://stackoverflow.com/a/127404/14065 But there are other problems with the code. – Martin York Jun 30 '12 at 02:32
  • This is pretty much the textbook example of why you need to implement deep copy and the rule of three. What you need is a copy of that textbook. – Jerry Coffin Jun 30 '12 at 02:32
  • Textbook [rule of three](http://stackoverflow.com/a/4172724/636019) violation. – ildjarn Jun 30 '12 at 02:58

2 Answers2

6

You have violated The Rule of Three

So, you make a copy of the object when you do

return *this

which gets destructed as well, and delete is called twice on the same pointer. You really shouldn't be doing this anyway. You should return a reference, but why should a setter function return a reference to the object it was called on anyway? Isd it to chain function calls?

Additionally, you are leaking Var every time you reassign it.

Ed S.
  • 122,712
  • 22
  • 185
  • 265
1

There are a few problems here.

First, the most direct cause of you problem is that a copy of the this object is made when SetVar() returns. (You probably want to return a reference to an A instead.) Since there is no copy constructor defined for class A, the values of all of the fields are implicitly copied. This means that the copy will have a pointer to the same Var int that you allocated in SetVar. In other words, you will have two pointers to the same memory, one in the original A variable (the one you call "Class") and one in the copy that is returned by SetVar(). When the second of these is destroyed, its destructor will be deleting the memory at an already-deleted pointer.

Turix
  • 4,470
  • 2
  • 19
  • 27