Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local variable deletes memory of another variable when going out of scope [duplicate]

While designing a class that dynamically allocates memory I ran into the following problem regarding memory allocation. I was hoping that some of you might be able to point me in the right direction as to how I should design my class in a better way. My class dynamically allocates memory and therefore also deletes it in its destructor.

In order to illustrate the problem, consider the following silly class declaration:

class testClass{
    int* data;
public:
    testClass(){
        data = new int;
        *data = 5;
    }
    ~testClass(){
        delete data;
    }
};

So far so good. Now suppose that I create one of these objects in main

int main(){
    testClass myObject;
    return 0;
}

Still no issues of course. However, suppose that I now write a function that takes a testClass object as an input and call this from main.

void doNoting(testClass copyOfMyObject){
    //do nothing
}
int main(){
    testClass myObject;
    doNothing(myObject);
    return 0;
}

This time around, the function creates a local variable, copyOfMyObject, that's simply a copy of myObject. Then when the end of that function is reached, that local object automatically has its destructor called which deletes the memory pointed to by its data pointer. However, since this is the same memory pointed to by myObject's data pointer, myObject inadvertently has its memory deleted in the process. My question is: what is a better way to design my class?

like image 772
pontus Avatar asked Feb 18 '23 07:02

pontus


1 Answers

When you call doNothing(), it is making a copy of your testClass object, because it is being passed by value. Unfortunately, when this copy is destroyed, it calls the destructor, which deletes the same data used by the original instance of testClass.

You want to learn about "copy constructors", and "passing by reference". That is, you should define a copy constructor for your class so that when a copy is made of an instance, it allocates its own memory for its data member. Also, rather than passing by value, you could pass a pointer or a reference to doNothing(), so that no copy is made.

like image 73
Kristopher Johnson Avatar answered Apr 08 '23 08:04

Kristopher Johnson