Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I *not* delete a member in a destructor?

I'd like the destructor of my class to delete the entire object except for one of the members, which is deleted elsewhere. First of all, is this totally unreasonable? Assuming it's not, how do I do this? I thought that created an destructor with an empty body would prevent all the members from being deleted (because the destructor wouldn't do anything), but that doesn't seem to be the case.

like image 932
Joe Avatar asked Jul 06 '09 17:07

Joe


People also ask

Does deleting a pointer call the destructor?

Default destructors call destructors of member objects, but do NOT delete pointers to objects. Thus, we need to write destructors that explicitly call delete.

What should be deleted in destructor C++?

The thing is to be noted here, if the object is created by using new or the constructor uses new to allocate memory which resides in the heap memory or the free store, the destructor should use delete to free the memory.

Is destructor delete?

When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.

Which operator is used to destruct the destructor?

Using destructors An object allocated using the new operator is explicitly deallocated using delete . The lifetime of a temporary object ends. A program ends and global or static objects exist. The destructor is explicitly called using the destructor function's fully qualified name.


1 Answers

Short answer: You don't.

Longer answer: If the "member" is actually a pointer to some other allocation, you can arrange to not delete the other allocation.

But usually, if you allocated the other block in the constructor, you want to delete it in the destructor. Anything else will require careful handling of the "ownership" of the block in question. It will be a lot like memory management in plain c. Possible, but fraught with danger.

Good luck.

like image 99
dmckee --- ex-moderator kitten Avatar answered Sep 21 '22 05:09

dmckee --- ex-moderator kitten