I think I know what the answer will be already but maybe someone knows alternatives.Destroy is used internally by the framework it is called automatically when a exception is raised inside a constructor for example. I would suggest to use interfaces instead of classes for your purposes.
What I would like to do is prevent the user of a library from calling the destructor of a certain classes. The use case is when the ownership is not on the user's end at all or when the user should not destroy the instance themselves but only mark it for deletion. In both cases it would be possible to at least give appropriate run time errors but better would be to have compiler errors.
I think I know what the answer will be already but maybe someone knows alternatives.
What I would like to do is prevent the user of a library from calling the destructor of a certain classes. The use case is when the ownership is not on the user's end at all or when the user should not destroy the instance themselves but only mark it for deletion. In both cases it would be possible to at least give appropriate run time errors but better would be to have compiler errors.
You can't. Even if you'd manage to "hide" Destroy for your class simply calling Free will result in the correct virtual method to be called. At worst you'll have memory leaks (e.g. if you used reintroduce and thus the normal, virtual Destroy won't call your destructor).Not quite It is possible (and I can also hide the warning and note:
You can't. Even if you'd manage to "hide" Destroy for your class simply calling Free will result in the correct virtual method to be called. At worst you'll have memory leaks (e.g. if you used reintroduce and thus the normal, virtual Destroy won't call your destructor).Not quite It is possible (and I can also hide the warning and note:
unit hidedestructor; {$mode delphi} interface type TBaseHiddenDestructor = class strict private destructor destroy;override; end; implementation destructor TBaseHiddenDestructor.Destroy; begin writeln('I am hidden'); end; end.
program testdestr; {$mode delphi} uses hidedestructor; type TTestClass = class(TBaseHiddenDestructor) end; begin with TTestClass.Create do free; end.
Not recommended, but possible... ;D And leaks...
PS C:\fpc\git> .\testoutput\tdestr.exe
I am hidden
udestr.pp(7,5) Warning: Destructor should be public
udestr.pp(7,16) Note: Virtual method "destructor destroy;" has a lower visibility (strict private) than parent class TObject (public)