use of struct vs class

Steven Schveighoffer schveiguy at gmail.com
Sat Mar 7 12:58:58 UTC 2020


On 3/7/20 5:58 AM, mark wrote:
> change #1:
> 
>                  if (line.empty) {
>                      if (deb != null && deb.valid)
>                          debs.insert(deb);
>                      else // report incomplete
>                      deb = null;
>                      continue;
>                  }
>                  if (deb == null)
>                      deb = new Deb;
> 
> change #2: gets rid of most errors:
> 
>      bool opEquals(const Deb* other) const @safe pure nothrow {
> 
>      int opCmp(ref const Deb* other) const {
> 
> Just changed to pointers & moved to a separate file.
> 
> So now I just have one error in line 12 of model.d:
> 
> RedBlackTree!Deb* debs; // name-ordered list of deb packages LINE 12
> 
> 
> Performing "debug" build using 
> /home/mark/opt/ldc2-1.20.0-linux-x86_64/bin/ldc2 for x86_64.
> gtk-d:gtkd 3.9.0: target for configuration "library" is up to date.
> debfind ~master: building configuration "application"...
> src/model.d(12,9): Error: template instance 
> std.container.rbtree.RedBlackTree!(Deb) does not match template 
> declaration RedBlackTree(T, alias less = "a < b", bool allowDuplicates = 
> false)
>    with T = Deb
>    must satisfy the following constraint:
>         is(typeof(binaryFun!less(T.init, T.init)))
> /home/mark/opt/ldc2-1.20.0-linux-x86_64/bin/ldc2 failed with exit code 1.
> 

Hm... I'd say:

1. Don't use a pointer for the element. Just use the struct directly. 
Using a pointer is bad because it's now going to compare pointers, and 
not the element data. Not only that, but RBNodes are stored as 
heap-allocated structs, so you are wasting a lot of memory by allocating 
another heap allocated thing to get stored inside there.

2. RedBlackTree allows you to identify the relationship that you 
consider unique by providing a "less" function. Instead of instrumenting 
your Deb type, which might affect other usages, just do:

RedBlackTree!(Deb, (a, b) => a.name < b.name)

No need to add opCmp and opEquals (if that doesn't make sense in other 
contexts).

-Steve


More information about the Digitalmars-d-learn mailing list