Interface reference counting

Top  Previous  Next

What is translated > Types > Records, Classes, Interfaces > Interfaces > Non-generic interfaces > Interface reference counting

In Delphi, interface instances are managed through automatic reference counting.

If an object that implements an interface is assigned to an interface-typed variable, it will be automatically destroyed when no more references to it exist.

 

Delphi2Cpp preserves this behavior in portable C++ by providing a custom smart pointer class:

 

template <typename T> class DelphiInterface<T>;

 

 

This class replicates Delphi’s reference model by providing:

 

RAII (automatic release when going out of scope)
Safe memory management and exception safety
Consistent lifetime control across all compilers
Clear ownership semantics for all IInterface-derived types

 

 

Portable C++ (non-C++Builder)

 

While raw IMyInterface* variables do receive automatic reference counting from the compiler, it is still recommended to use DelphiInterface<T>.
Benefits: RAII, exception safety, and consistent behavior between C++Builder and portable builds.

 

DelphiInterface<IMyInterface> Intf = new TMyClass();

Intf->DoSomething();

// Calls Release() automatically when going out of scope

 

 

C++Builder

 

Interface variables (e.g., IMyInterface*) are implicitly managed by the compiler.
No need to use DelphiInterface<T> explicitly.
Even raw interface pointers receive correct AddRef / Release semantics.

 

DelphiInterface<IMyInterface> Intf = new TMyClass();

Intf->DoSomething();

// Safe and consistent with portable mode

 

 

 



This page belongs to the Delphi2Cpp Documentation

Delphi2Cpp home  Content