Andrei Alexandrescu wrote:
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.

I'd really like to know why "scope x = new X();" is "unsafe", while encouraging doing exactly the same with structs seems to be a perfectly fine idea. Allocating structs on the stack is obviously not any safer than with classes. I don't remember the exact reasons why you wanted to turn "scope" into a library feature, but I think I remember something about discouraging it for safety reasons; please forgive me is this is wrong.

Why do you want to add class functionality to structs to enable "RAII" like features, when you could just use scope classes?

To refresh everyone's memory: a scope class is declared like "scope class Foo { ... }", and references to it can "only appear as a function local variable".

I for one don't really like the idea of having to distinguish between PODs and "other stuff" (like you had in C++) just again.

At the very least, the default constructor should always be available for structs. (If not, have fun figuring out what S[10] should do.)

Andrei

Reply via email to