[fpc-devel] "Default" discussion for SmartPointers etc

Michael Van Canneyt michael at freepascal.org
Thu Jul 28 17:58:55 CEST 2016



On Thu, 28 Jul 2016, Maciej Izak wrote:

> 2016-07-28 16:37 GMT+02:00 Michael Van Canneyt <michael at freepascal.org>:
>>
>> Are there additional benefits I have missed ?
>>
>>
> Using nilable (I think nilable is better than nullable) records is terrible
> without default field:
>
> === code begin ===
>
> var
>  n: TNilable<TRec>;
>  x: TRec;
> begin
>  {
>
>   ... let say that n is assigned somewhere, assume that n.HasValue = true
>
>  }
>  // to change any field in nilable n  you need to...
>  x := n.Value;


OK, you convinced me for this one :-)

Michael.

>
> that will change nothing, just look below. Just harder to usage pure
> non-pascalish clone of C# struct (finally C# has pointers as
> nonstandard/unsafe type so feature with direct dereference is disabled by
> design).
>
> === code begin ===
>
> procedure SomeTest(x : Integer);
> begin
> end;
>
> Var
>  A : TNullable<Integer>;
> begin
>  SomeTest(A.Value); // AV error here!
> end.
>
> === code end ====
>
> A^ is shortcut for A.Value but has advantage = direct dereference to
> Instance.

Here I am not convinced.

This is an artifact of your implementation: you use a pointer. 
There is no need to use a pointer. One can just as well do

TNullable <T> = Record 
Private
   Fvalue : T;
   IsNotNull : Boolean;
Public
   // all the rest, including
   Property Value : T Read GetValue Write SetValue;
   Property IsNull : Boolean Read GetIsNull;
end;

Then you will not have this problem; 
GetValue will always return a 'Default' value.

Michael.



More information about the fpc-devel mailing list