this() not executing code on structs

dsimcha dsimcha at yahoo.com
Wed Oct 21 15:14:23 PDT 2009


== Quote from grauzone (none at example.net)'s article
> Andrei Alexandrescu wrote:
> 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.

Because classes in D are always passed by pointer.  (Technically references, but
really they're just pointers under the hood.)  Returning a scope (stack-allocated)
class from a function is equivalent to escaping a pointer to a stack variable.
Returning a struct is done by value, just like returning an int.

Classes can't be value types because they are polymorphic, meaning their size
isn't known at compile time.  C++ tries to make them value types but really, there
is no *good* way to make a polymorphic type with size not known at compile time a
value type.

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

To me, this makes perfect sense.  Classes are polymorphic, structs are value
types.  Except in the "here be dragons" world of C++, the two are mutually
exclusive, which is the reason for the dichotomy in the first place.  Therefore,
structs should do everything they can w/o being polymorphic and classes should do
everything they can w/o being value types.  You then decide which one you want
based on whether you need value semantics or polymorphism more.

The only place in D where this logic breaks down is monitor objects on classes.
Even here, while structs technically *could* be given monitors, this is
inefficient because they are value types, whereas the efficiency loss from storing
a few extra bytes in a reference type is minimal in most cases.

Scope is really a dangerous hack to allocate a *reference type* on the stack.
It's dangerous and kludgey, but in a performance-oriented language it's a
necessary evil.



More information about the Digitalmars-d mailing list