如何避免内存泄漏与未记录的运算符重载类?

时间:2017-10-11 09:45:30

标签: delphi operator-overloading undocumented-behavior

Delphi有许多记录的运算符重载:

对于recordsARC_classes(在NexGen编译器中) 正式地说,它不支持类,接口或简单类型的运算符重载。

...除

There are undocumented operator overloads 执行在界面classessimple types上工作。
(虽然无证件的操作员似乎不在记录上工作)。

E.g。以下代码将编译并运行:

Win32 / 64中类的运算符重载

//sorry for the horrible use of `or` to use for nil testing.
//I'd code this into a function (function FirstAssigned(a,b: TObject): TObject;
//It's just an example to demonstrate the concept. 
type
  TObjectHelper = class helper for TObject
  public
    class function &&op_LogicalOr<T: class>(A, B: T): T; static;
  end;

class function TObjectHelper.&&op_LogicalOr<T>(A, B: T): T;
begin
  if A <> nil then
    Result := A
  else
    Result := B;
end;

procedure Test;
var
  sl1, sl2, sl3: TStringList;
begin
  sl1 := nil;
  sl2 := TStringList.Create;
  sl3 := sl1 or sl2; // -> sl3 = sl2
end;

供参考,以下是所有允许运营商的列表:

List of operators

class operator      class function          example
---------------------------------------------------
Implicit            &&op_Implicit           x:= y;
Explicit            &&op_Explicit           x:= integer(y);
Negative            &&op_UnaryNegation      x:= -y
Positive            &&op_UnaryPlus          x:= +y
Inc                 &&op_Increment          Inc(x);
Dec                 &&op_Decrement          Dec(y);
LogicalNot          &&op_LogicalNot         Not(y); //can be used for bitwise not as well
Trunc               &&op_Trunc              i:= trunc(f);
Round               &&op_Round              i:= round(f);
In                  &&op_In                 if (i in s) then
Equal               &&op_Equality           a = b
NotEqual            &&op_Inequality         a <> b
GreaterThan         &&op_GreaterThan        a > b
GreaterThanOrEqual  &&op_GreaterThanOrEqual a >= b 
LessThan            &&op_LessThan           a < b
LessThanOrEqual     &&op_LessThanOrEqual    a <= b
Add                 &&op_Addition           a + b
Subtract            &&op_Subtraction        a - b
Multiply            &&op_Multiply           a * b
Divide              &&op_Division           a / b //floating point div
IntDivide           &&op_IntDivide          a div b //integer div
Modulus             &&op_Modulus            a mod b
LeftShift           &&op_LeftShift          a shl b
RightShift          &&op_RightShift         a shr b
LogicalAnd          &&op_LogicalAnd         if (a and b) then ...
LogicalOr           &&op_LogicalOr          if (a or b) then ....
LogicalXor          &&op_ExclusiveOr        if (a xor b) then
BitwiseAnd          &&op_BitwiseAnd         x:= a and b
BitwiseOr           &&op_BitwiseOr          x:= a or b
BitwiseXor          &&op_BitwiseXOR         x:= a xor b
Include             &&op_Include            include(s, i);
Exclude             &&op_Exclude            exclude(s, i);

在(非弧)类中使用这些重载时,如何避免遇到内存泄漏?

0 个答案:

没有答案