Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guarantee initialisation of stack record

I want to fix a design flaw in a record TMyValue that has been in use for years, and I desperately want to fix it in the record itself - to avoid changing the public interface - and not require the code using the record to be changed.

Essentially, the flaw is that a TMyValue must be initialised to zero when it is created, otherwise calling the Clear method on it can cause a crash. This is because it contains a field that is a pointer to dynamically-allocated memory if the pointer is non-nil, and Clear causes the dynamic memory to be freed.

This is a problem if the TMyValue is created on the stack, because stack variables are not zeroed out automatically when they are created.

I thought I could use a record constructor to zero out the record, but record constructors cannot be parameterless. Presumably this means that you cannot force a record constructor to be executed automatically when a record is created on the stack.

I suspect the answer to my question is "it cannot be done". Please prove me wrong!

like image 211
Ian Goldby Avatar asked Jun 04 '13 08:06

Ian Goldby


1 Answers

Add a dummy string member into your record. Since a string is a managed type it will be initialized to an empty string when the record comes in scope.

So when calling your Clear method, test if the dummy string is empty first. Set the string to a value when appropriate to the use logic to mark the record as initialized.

like image 62
LU RD Avatar answered Nov 10 '22 05:11

LU RD