Today, structs can't write their own this(). There aren't very solid reasons for that except that it makes language implementation more difficult.

I wonder how much of a problem that could be in practice. I realized today that the "Counted" example - a classic C++ primer example featuring a struct that counts its own instances - cannot be implemented in D.

In C++ the counted example looks like this:

struct Counted {
   static unsigned count;
   unsigned myCount;
   Counted() { myCount = count++; }
   Counted(const Counted& rhs) { myCount = count++; }
   Counted& operator=(const Counted& rhs) {
      // no writing to myCount
      return *this;
   }
   ~Counted() {
      --count;
   }
}

In D there's no chance to write Counted because you can always create Counted objects without executing any code.

struct Counted {
   static uint count;
   uint myCount;
   this() { myCount = count++; }       // ERROR
   this(this) { myCount = count++; }
   ref Counted opAssign(Counted rhs) {
      // no writing to myCount
      return this;
   }
   ~this() {
      --count;
   }
}

This being a toy example, I wonder whether there are much more serious examples that would be impossible to implement within D.


Andrei

Reply via email to