Time to kill T() as (sometimes) working T.init alias ?

Jonathan M Davis jmdavisProg at gmx.com
Sun Dec 9 11:16:24 PST 2012


On Sunday, December 09, 2012 10:58:45 Walter Bright wrote:
> On 12/8/2012 5:00 PM, Mehrdad wrote:
> > Copying objects ought to be expensive.
> 
> I don't understand the rationale for that.

I can see an argument that there's no requirement that copying objects be 
cheap, since there are plenty of objects where it's _not_ cheap to copy them 
and where it can't be cheap to copy them, but I don't see any argument for 
them _supposed_ to be being expensive to copy. I suspect that Merhdad just 
phrased it incorrectly.

D and Phobos seem to be trying to take the tact that copying objects is 
supposed to be cheap and expect it to be cheap. But I honestly don't see how 
anyone can expect that to be relied upon. There are things that can be done to 
reduce the cost of copying an object (like COW), but l think that if you 
honestly expect that people aren't going to do stuff like

this(this)
{
    a = a.dup;
}

then you're deluding yourself. That's kind of the point of having posblits in 
the first place, and it's basically the example that TDPL gives as to what 
postblits do. And depending on the type of a's elements, that copy could be 
far worse than O(1). And even if it weren't, there's nothing stopping the 
programmer from doing other expensive operations in a postblit constructor 
(e.g. doing a deep copy of a red-black tree by recursively copying the whole 
thing).

I'm fine with saying that various algorithms will be far more expensive if your 
struct defines an expensive postblit and that defining an expensive postblit is 
best avoided if possible, but there _will_ be plenty of expensive postblits in 
real world code. The only way that you can guarantee that copying structs is 
cheap is if you make it impossible to do a deep copy (i.e. get rid of 
postblit), which would be _far_ too limiting. Even stuff like ref-counted 
structs would become impossible in that case, because it's postblit which 
makes them possible as well.

- Jonathan M Davis


More information about the Digitalmars-d mailing list