How to make destructors safe for the entire class hierarchy?

I would like to make sure that no one can delete any objects from my class hierarchy, in addition, using the provided Destroy method.

The rationale is that any object from this hierarchy must accept a special record mutex before it begins to destroy itself, to make sure that the objects are not deleted, and that another thread uses them.

I know that I can prevent this problem with reference counting, but it will be a much bigger change in the system also in terms of potential impact on performance and memory allocation.

Is there any way to effectively / intelligently protect all destructors in such a way that child classes can call their parents destructors and outsiders should use Destroy?

One safe solution (i.e., it will not rot) that I came up with is to make all destructors private and declare each derived class as a friend of the base class, but I would prefer something more elegant, manual and easier to maintenance (for example, you do not need to modify the base classes to receive from them).

Is there anything similar? Maybe some clever trick that makes things "work" as I would like?

ps. The solution I chose at the moment is to NOT prohibit anyone from calling delete in all cases (he was just protected in the base class), but he discovered this situation and caused an interrupt in the base class destructor.

+5
source share
4 answers

Do not try to invent life-time mechanisms provided by the language.

In order for your class object to be properly initialized, it must also be able to clean itself.

Either a mutex or a means of obtaining a mutex passes in its constructor, which it can use in its destructor.

+1
source

. - , :( ( "" , "" ).

( , / ( ..))

  • ,
  • Destroy , - , ,
  • ( ) - , , - - ( ..) - , , /.
+1

, . BaseObject. . BaseObject , , : retain(), release() autorelease(), Objective-C. delete release(), 0. delete , BaseObject .

, protected private. , , , Perl script, . , .

script, : https://gist.github.com/prapin/308a7f333d6836780fd5

+1

. 2 :

  • ( ),
  • ( ), , .

If both test cases work, I think you can be sure that your classes are protected as you like.

I don't know if you can implement it with your build system, but I have an example of using bjam (from boost) in a git hub . The code is simple and works for gcc and msvc. If you do not know bjam, you should look at intam Jamroot.jam. I think that without unnecessary comments it is clear how this simple example works.

0
source

All Articles