Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make destructors protected for a whole class hierarchy in a maintainable way?

I would like to make sure no one is able to delete any objects from my class hierarchy other then by using a provided Destroy method.

The rationale is that any object from this hierarchy needs to take a special write mutex before it starts to destroy itself to make sure objects are not deleted while another thread is using them.

I know I could prevent this problem with reference counting but it would be a much bigger change to the system also in terms of potential performance impact and memory allocation.

Is there a way to somehow efficiently/smartly make all the destructors protected so that child classes can call their parents destructors while outsiders have to use Destroy?

One solution that is safe (ie. it will not rot) that I came up with is to make all the destructors private and declare each derived class as a friend of the base class but I'd prefer something more elegant, less manual and easier to maintain (like not requiring to modify base classes in order to derive from them).

Is there anything like this available? Maybe some smart trick that makes things "work" as I'd like?

ps. The solution I chose for now is to NOT prevent anyone from calling delete in all cases (just made it protected in the base class) but detect this situation and call abort in the base class destructor.

like image 791
RnR Avatar asked Oct 21 '22 15:10

RnR


1 Answers

Don't try to reinvent the lifetime mechanisms provided by the language.

For an object of your class to be correctly initialised it needs to also be able to clean itself up.

In its constructor pass either the mutex, or a means of obtaining a mutex, which it can use in its destructor.

like image 126
Peter Wood Avatar answered Nov 15 '22 05:11

Peter Wood