Destruction of function parameters

This has been bothering me for some time now:

I have a very small class (just 4 bytes in size), which I figured wouldn't be to harmful passing it as a parameter. One of it's members is a pointer to an array of data, that I delete using delete[] inside the classes destructor. When I now pass the class as a function's parameter, I guess a flat copy is made and stored on the program stack. Therefore no overloadable operator gets called and the pointer inside my class stays the same. After the function finishes, my destructor gets called, which removes my array. Outside this function the original class therefore now has a dangling pointer (it points to already removed memory).

Is there any way I can capture this copying to the stack, so that I can increase a reference counter?

Here a piece of code for clarification:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class MyClass
{
    byte* ptrData;

    MyClass()
    {
        ptrData = new byte[100];
    }
    ~MyClass()
    {
        delete[] ptrData;
    }
};

void CallingFunction()
{
    MyClass myclass; // Constructor gets called
    CalledFunction(myclass);

    myclass.ptrData[50] = 123; // Memory leak
}

void CalledFunction(MyClass myclass)
{
    myclass.ptrData[50] = 123; // Everything fine

    return; // Destructor gets called
}
You need to implement copy constructor and assign operator.

You problem happen because a function that takes parameters by value(it's your case) call copy constructor. If you don't declare copy constructor by yourself then it does compiler.
So compiler does not know that your class keeps pointer, so it just copies the address of the pointer to the another object. And in this situation you have two object that keep pointers on the same address. When the first object is going to destroy it call delete for this pointer, then the second object is going to destroy and try to call delete again for the same pointer.
Last edited on
Thanks a lot, Denis.

I spent hours going through all the constructors and I guess the copy constructor was pretty much the only one I didn't try.
Denis said it all. Whenever your class is using pointers it is almost always necessary to provide a copy c'tor and assignment operator overload.
Topic archived. No new replies allowed.