general questions on reference types versus value types...

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Nov 30 21:00:05 PST 2014


On Monday, December 01, 2014 04:42:36 WhatMeWorry via Digitalmars-d-learn wrote:
>
> Is it correct to say that D reference types (classes, dynamic
> arrays, etc.) are always allocated on the heap; whereas D value
> types (structs, static arrays, etc.) are always allocated on the
> stack?  Or is this a gross oversimplification?
>
> Because can't structures contain classes and classes contain
> structures?
> If so, how should one thinks about these hybrid types?  Does the
> outermost type take precedent over what ever it contains?
>
> Can't resist this. Maybe I should just create a play code, but
> could a Structure contain a class that contained a structure that
> contained a class that...  Not sure why one would ever need to,
> so just a theoretical question.

Structs can go on the heap. e.g.

MyStruct* s = new MyStruct("foo");

And structs can be reference types. e.g.

struct MyStruct
{
    Object o;
}

So, ultimately, while it's true on the surface that structs are value types,
classes reference types, etc., the reality is a bit more complicated. Even
arrays aren't really one or the other, because while slices refer to the
same data, mutating the array object itself of one slice does not alter the
array object of another slice.

So, strictly speaking, something is a value type if assigning it to another
variable or initializing another variable with it does a full, deep-copy.
e.g.

Type t;
Type u = t;

But even that gets a bit fuzzy once stuff like immutable gets involved,
because if you have

struct MyStruct
{
    string s;
}

auto s = MyStruct("foo");
auto t = s;

then t is a copy of s, because the reference portion is immutable and thus
can't be mutated.

Really, talking value types and reference types at the basic level is pretty
straightforward and fairly clear, but once you get down into it, things get
a _lot_ more complicated.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list