If the type of Data
is TObject
then you cannot avoid memory management issues. The compiler is not going to manage the lifetime of a TObject
instance for you. You will have to use one of the standard lifetime management mechanisms:
- You take care of it with try/finally blocks, and explicit calls to
Free
. - You derive your object from
TComponent
and let it be owned by something that is guaranteed to outlive all references to your wrapped string.
Option 2 has a number of variants. Other ways to hand off ownership include using interfaces. So long as the owner outlives all references to the object then you are safe.
Personally I don't very much like option 2. If the compiler isn't going to manage the lifetime of my objects, I prefer to manage it myself. I find that if I use explicit management then it is easier to reason about when my objects' lives end.