Struct that destroys its original handle on copy-by-value

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jul 31 11:20:09 PDT 2015


On Fri, Jul 31, 2015 at 06:01:44PM +0000, Dicebot via Digitalmars-d-learn wrote:
> On Friday, 31 July 2015 at 17:21:40 UTC, Ali Çehreli wrote:
> >On 07/26/2015 04:29 AM, Joseph Rushton Wakeling via Digitalmars-d-learn
> >wrote:
> >
> >> is this design idea even feasible in principle, or just a bad
> >> idea from the get-go?
> >
> >As I understand it, it is against one of fundamental D principles:
> >structs are value types where any copy can be used in place of any
> >other.
> >
> >I expect there are examples where even Phobos violates it but the
> >struct documentation still says so: "A struct is defined to not have
> >an identity; that is, the implementation is free to make bit copies
> >of the struct as convenient."
> 
> I believe this restriction should be banned. Considering classes have
> inherent reference + heap semantics (and you can only bail out of that
> with hacks) saying struct can't be anything but data bags makes
> impossible to implement whole class of useful designs.
> 
> The fact that Phobos has to violate it itself to get stuff done is
> quite telling.

On the other hand, though, structs that are *not* mere data bags usually
get into the dark area of compiler bugs and other unexpected
side-effects or unclear areas of the language, often with questionable
or inconsistent behaviour. My suspicion that these problems aren't just
because of compiler quality or the language spec being incomplete, but
it's because they are caused by this underlying dichotomy between
structs being defined to be purely data, and structs being used for
things that are more than just pure data.

One example of this is how long it took for std.stdio.File to get to its
present form. It started out as a "simple" wrapper around the C library
FILE*, passed through stages of being "pure data" yet showing buggy
corner cases, then stepping into dtor territory with its associated
unexpected behaviours, then now into a wrapper around a ref-counted type
(and IIRC, it may still show buggy / odd behaviour when you stick it
inside a container like an array).  Along the way, we had issues with
dtors, postblit, and a whole slew of issues, almost all of which can be
traced back to the dichotomy between a struct wanting to be "just a
value" yet at the same time wanting / needing to be more than that.

It seems that what the language (originally) defines structs to be, is
not entirely consistent with how it has come to be used (which also
entailed later extensions to the struct definition), and this has been a
source of problems.


T

-- 
Bare foot: (n.) A device for locating thumb tacks on the floor.


More information about the Digitalmars-d-learn mailing list