简体   繁体   中英

deleting object that was initialized by dereferencing new object

I've got the following class:

now I've been thinking of implementing my constructor this way:

basically dereferncing the object returned by the new operation. now... this feels wrong and I should probably should have be working with pointers, but I'd like to challange myself to maybe get this to work and learn something new.

So my problem will be deleting this object... my destructor for Dense does not work as I have it like this:

but obviously I'm getting this error:

free(): invalid pointer

so how can I go about freeing the allocated memory with the way I have this implemented?

Thanks.

There is no need to do it this complicated. You can call the constructors directly from the initializer list. There is absolutely no need for new here. Also you don't need to delete those objects. Their destructors will be called automatically if Dense gets destroyed.

Dense::Dense(): weights(), //Calls constructor Matrix()
                bias(), //Calls constructor Matrix()
                act(ActivationType::Relu), //Calls constructor Activation(ActivationType::Relu)
                input() //Calls constructor Matrix()
{}


Also, what you are trying to do with pointers wont work. For example &bias will be the address of the member variable bias and has nothing to do with the pointer returned by new Matrix() .

so how can I go about freeing the allocated memory with the way I have this implemented?

You simply can't and you have created a memory leak.


Explanation:

When you write:

int a = *(new int(5)); // Really bad

You basically:

  • allocate an int on the heap
  • dereference the r-value
  • assign it (copy) to a variable on the stack

At no moment you did care to keep the returned pointer of the new statement. a is another int that is a copy of what you've allocated on the heap.

You can't delete a because it is created on the stack. As a is another object, the address of a is not the same as the address of the int you've allocated on the heap with new .

So deleting &a is obviously forbidden Undefined Behaviour and cannot in any way delete the int that you've created with new . And as you did not stored the returned pointer of the new statement, you have no way to retrieve it: This is a memory leak.


If you got a reference instead of a copy, you would be able to delete it:

int & a = *(new int(5));
delete &a; // fine

But it is an over-complicated, less efficient and pointless way of simply doing:

int a = 5; // destroyed at scope's end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM