Classes or stucts :: Newbie

Jonathan M Davis jmdavisProg at gmx.com
Sun Dec 19 17:26:20 PST 2010


On Sunday 19 December 2010 16:50:34 Nick Voronin wrote:
> On Sun, 19 Dec 2010 14:38:17 -0800
> 
> Jonathan M Davis <jmdavisProg at gmx.com> wrote:
> > On Sunday 19 December 2010 14:26:19 bearophile wrote:
> > > Jonathan M Davis:
> > > > There will be a library solution to do it, but again, it's unsafe.
> > > 
> > > It can be safer if the compiler gives some help. For me it's one of the
> > > important unfinished parts of D.
> > 
> > Whereas, I would argue that it's completely unnecessary. structs and
> > classes serve different purposes. There is no need for scoped classes.
> > They may perodically be useful, but on the whole, they're completely
> > unnecessary.
> 
> How do you define a need for scoped classes?
> 
> I see two aspects there: first is having destructor called at known point
> rather than arbitrarily, second is performance.
> 
> It looks perfectly reasonable for me to want to have first. Do you know why
> things which makes program act more deterministic are shunned from D? Does
> it really add so much to safety that it is worth reducing programmer's
> control?

Then use a struct. That's one of the reasons that they exist. And if you 
_really_ want to make sure that a class' destructor gets run, you can always use 
clear() (which is arguably an abomination in its own right). And if you use that 
in combination with scope(exit), then you get a class which is guaranteed to be 
destroyed when the function exits, and (assuming that clear() is fully 
implemented and actually zeroes out the vtable - which I don't think that it 
does yet), you won't be using garbage memory (though obviously it will still go 
boom - likely due to a segfault).

Part of the whole point of separating classes and structs is to separate the 
issue of where they go - on the stack or on the heap. So, putting classes on the 
stack kind of negates the whole point of having both structs and classes in the 
first place.

> In _general_ case there is no safety in D. With all low-level capabilities
> one can always defeat compiler. Removing intermediate-level safer (yet
> unsafe) capabilities arguabily gains nothing but frustration. I'm all for
> encouraging good practices, but this is different.

In the general case when using SafeD, there D _is_ safe. scoped classes are 
definitely not in SafeD.

structs already are on the stack. If you want something on the stack, then use 
structs. And if you _really_ want a class on the stack for whatever reason 
(which I _really_ question), then there will be a library solution to the 
problem. By putting classes on the stack, you're pretty much ignoring the 
differences between structs and classes.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list