this() not executing code on structs

Rainer Deyke rainerd at eldwood.com
Wed Oct 21 14:02:46 PDT 2009


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.

Any struct that uses dynamic memory allocation internally.

Any struct that registers its instances in some dort of global registry.

'ValueType!T', which turns reference type 'T' into a value type.

A 'ScopedLock' variant that uses a single global mutex.

RAII wrappers over global initialization/deinitialization functions.

A 'UniqueId' struct that initializes to a value that is guaranteed to be
distinct from the vale of any other 'UniqueId' used by the program.


-- 
Rainer Deyke - rainerd at eldwood.com



More information about the Digitalmars-d mailing list