Wednesday 4 December 2019

c++ - What happens when you use "new" twice on the same object?




Lets say we have this..



class MyClass
{
int value;

void addIntToObject(int num)
{
value = num;
}

}


MyClass *object = new MyClass();
object->addIntToObject(1);
object->addIntToObject(2);


Now let's say we do this again...



object = new MyClass();


By using new twice on the same object, does that mean we have deleted all data that was stored in object? can someone explain to me the exact workings of using new twice on the same object



Would this be an efficient way to free memory? (like using delete and delete[])


Answer



You didn't "do new twice on the same object". The new expression creates an object. By doing new twice you made two entirely separate objects.



The variable object is a pointer. It points to other objects. The = operator on a pointer means to change which object the pointer is pointing to.



So in your code there are two objects, and you change object (the pointer) to point to the second object. The first object still exists but nobody knows where it is, this is known as a memory leak.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...