Rationale for classes as reference types

Bill Baxter wbaxter at gmail.com
Thu Aug 7 11:43:50 PDT 2008


On Fri, Aug 8, 2008 at 1:10 AM, Steven Schveighoffer
<schveiguy at yahoo.com> wrote:
> "A Lahav" wrote
>> Can anyone please explain the design rationale for classes being reference
>> types exclusively?
>>
>> I ask this because I really like my classes to be allocated on the stack
>> or be value-type data members, the performance boost you get eliminiting
>> all these unnecessary heap operations is entirely not neglible.
>>
>> Otherwise I'll have a real problem considering D for my own use...
>
> Because of many reasons Walter has described in the past.  The one that
> sticks out to me is the chopping effect (don't know if this is the right
> term).  Let's say a function returns a non-reference class instance, and
> your function returns a derived instance.  The return value chops off the
> derived stuff.

It's called "slicing".

> I like the way classes are always references.  But there is a way to ensure
> a class gets allocated on the stack:
>
> scope c = new MyClass(...);
>
> This will allocate the class on the stack.  Be sure not to return a
> reference to it later though!
>
> Another possibility is to use structs instead, which do not have
> inheritance, and so will not cause the chopping effect.

As has been mentioned in the past, it would definitely be nice if you
could also make a "scope MyClass" as a member of another class or
struct.

--bb


More information about the Digitalmars-d-learn mailing list