[fpc-devel] Copy/move operator
Ben Grasset
operator97 at gmail.com
Tue Jun 18 15:33:36 CEST 2019
On Mon, Jun 17, 2019 at 5:57 PM Ryan Joseph <genericptr at gmail.com> wrote:
> The copy operator is always called on all assignments. Try actually
> running that and you’ll see. :)
>
Yeah, I noticed that afterwards once I checked. I'm not sure how much sense
that actually makes when the TList<T> is a function *result* as it is in
the static class function version of Create, though (i.e, you're not
assigning an existing TList<T> variable to another, you're returning a
brand new one.)
The version of Copy in my last comment was missing a SetLength, also, and
called `Move` incorrectly. Something like this is what I was going for:
program Test;
{$mode ObjFPC}
{$modeswitch AdvancedRecords}
type
generic TList<T> = record
public
Data: array of T;
class operator Copy(constref Src: TList; var Dest: TList); inline;
class function Create(const Num: Integer): TList; static; inline;
end;
class operator TList.Copy(constref Src: TList; var Dest: TList);
var Len: SizeInt;
begin
Len := Length(Src.Data);
SetLength(Dest.Data, Len);
Move(Src.Data[0], Dest.Data[0], SizeOf(T) * Len);
end;
class function TList.Create(const Num: Integer): TList;
begin
SetLength(Result.Data, Num);
end;
begin
// Do whatever here.
end.
Don't forget about your constant generics feature, also... can help in
avoiding "constructorish" things altogether quite a bit.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-devel/attachments/20190618/3984f604/attachment.html>
More information about the fpc-devel
mailing list