As one of the good guys (Agustín Ortu) recently pointed about one very tricky thing about const parameters and interfaces I decided that it is worth to share that with all of you.

So imagine you have the following code:

IHandler = interface ... THandler = class(TInterfacedObject, IHandler) ... procedure DoSomething( CONST AHandler: IHandler); begin { No code accesses the AHandler } end; ... DoSomething(THandler.Create)

Looks safe, isn’t it?

NO. There is a potential memory leak. because if no code addresses the AHandler inside of the routine DoSomething you will get a leak of the THandler instance!

Why this happens:

THandler is constructed – it’s just plain object of TInterfacedObject type; It is passed as pointer to the DoSomething function (as it is const). So no reference is added and the FRecCount = 0; So now if no code is accessing the AHandler as IHandler type the reference count will not take place and the object is leaked!

How to avoid:

Define the parameter as non-const (that’s the best – and don’t cry about “redundant” calls to _AddRef, _Release) – as then once the code enters function the reference will be added and once scope is left the object will be released and there will be no memory leak; Always assign the first the reference to the local variable and then pass it to the parameter; Write DoSomething(THandler.Create as IHandler); Make a constructor function like NewHandler: IHandler and make the explicit creation there (like NewXMLDocument function).

Which one to choose is your business.

But you need to take care when you choose to use the const prefix for the parameter of interface type and consider reading about parameters!

Have a nice Friday!