Classes or stucts :: Newbie

Nick Voronin elfy.nv at gmail.com
Sun Dec 19 13:11:49 PST 2010


On Mon, 20 Dec 2010 07:00:31 -0800
David Currie <curriedr at iinet.net.au> wrote:

> Can a class be instantiated on the stack ?

Yes, check std.conv.emplace http://www.digitalmars.com/d/2.0/phobos/std_conv.html#emplace and alloca()
I don't know details about interaction of such objects with GC though.

Also there is scarcely documented storage class scope, which for class objects means that they will be destroyed upon scope exit, but also currently results in that object itself will be placed on the stack, no memory in heap is allocated.

>    C myC(3);  // C++ syntax BUT is there a d equivalent
> It appears that D ASSUMES myC is really a myC*(in C++)

Not exactly. All class objects have reference semantic, so when you declare variable of type C you really declare a reference. The reference is what you get from new, pass as parameters, etc.

> Will a struct do?

structs on the contrary have value semantic, so when you declare struct variable you get the memory for struct allocated on stack or in data segment. When you pass or return structs -- you return or pass value, that is a copy of data.

You may be also interested in the way dynamic arrays are handled, as arrays are value type, yet they hold a pointer to memory. This means that passing them as parameter or returning them does copy pointer and length, but actual data is stil shared until you do something which will force D to relocate it. All kind of not obvious implications here.

> Does a struct have a constructor (as opposed to an opcall?)

Yes, and more. http://www.digitalmars.com/d/2.0/struct.html

-- 
Nick Voronin <elfy.nv at gmail.com>


More information about the Digitalmars-d-learn mailing list