[fpc-devel] Copy/move operator
Ben Grasset
operator97 at gmail.com
Mon Jun 17 23:16:51 CEST 2019
On Sun, Jun 16, 2019 at 9:30 AM Ryan Joseph <genericptr at gmail.com> wrote:
> Here’s a little example of the problem. What I propose is that we either
> add a 3rd boolean parameter to the Copy operator or add a new Move operator
> which is preferred over the Copy operator if it exists (this is much more
> work obviously but maybe has some benefit).
>
I can't actually check the assembly at the moment, but I'm pretty sure if
your example was written like the following, it would not call `Copy` for
the `TList<Integer>.Create(10)` assignment:
{$mode objfpc}
{$modeswitch advancedrecords}
program test;
type
generic TList<T> = record
data: array of T;
// static class function instead of actual constructor
class function Create(num: integer): TList; static; inline;
class operator Copy(constref src: TList; var dest: TList);
end;
class function TList.Create(num: integer): TList;
begin
SetLength(result.data, num);
end;
class operator TList.Copy(constref src: TList; var dest: TList);
begin
// no reason not to use `move` here, I wouldn't say
move(src.data, dest.data, sizeof(T) * Length(src.data));
end;
var
a, b: specialize TList<integer>;
i: integer;
begin
// TList.Create allocates a new array but we don’t really need to copy
// on assignment because the source is a temporary object that doesn’t
// actually exist at any static address.
a := specialize TList<integer>.Create(10);
for i := 0 to 9 do a.data[i] := i;
b := a;
for i := 0 to 9 do writeln(b.data[i]);
end.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-devel/attachments/20190617/8add9404/attachment.html>
More information about the fpc-devel
mailing list