How do you make a copy TO and object when you're INSIDE of it?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jul 23 20:12:43 PDT 2015


On 7/23/15 9:30 PM, Enjoys Math wrote:
> Here's my code:
>
> module grammar;
>
> class Grammar(T : ulong) {
>      this(const T[] str) {
>          auto grammar = str in grammarCache;
>
>          if (grammar) {
>              this = grammar.dup;
>          } else {
>              this = approximateSmallestGrammar(str);
>              grammarCache[str] = this.dup;
>          }
>      }
>
>      static Grammar approximateSmallestGrammar(const T[] str) {
>          return new Grammar();
>      }
>
>      @property Grammar dup() {
>
>      }
>
> private:
>      this() {}
>      static Grammar[T[]] grammarCache;
> };
>
>
> Compiler says 'this' is not an lvalue.  How would I accomplish what I want?
>

You're approaching this wrong. Do the lookup before deciding whether to 
instantiate a new object:

static Grammar getGrammar(const T[] str) {
      if(auto x = str in grammarCache)
          return *x;
      else
      {
          auto g = new Grammar;
          grammarCache[str] = g;
          return g;
      }
}

If you always want to dup, then do it outside the lookup. Don't do it in 
the constructor, you already have an object by then.

-Steve


More information about the Digitalmars-d-learn mailing list