const as default for variables

Zach the Mystic via Digitalmars-d digitalmars-d at puremagic.com
Tue Mar 17 23:24:37 PDT 2015


On Tuesday, 17 March 2015 at 22:53:20 UTC, deadalnix wrote:
> On Tuesday, 17 March 2015 at 22:25:30 UTC, Zach the Mystic 
> wrote:
>> The real devil against safe reference counting is in the 
>> assignment operators, when they do destructive moves. I think 
>> those have to be the focus of any effort here.
>>
>> I'm trying to imagine a parameter attribute `@destroy`, for 
>> example, indicating that its reference may get destroyed. Not 
>> sure if it will work, or even help, but it's a start.
>
> That is the wrong approach. This is a know problem and there is 
> a known solution: ownership. If we are going to add something 
> in the language to handle it, then it has to be ownership.

Just so we're clear, there are two problems. One is making 
ref-counting safe. The other is making it fast, by eliding 
unnecessary operations. The issue I'm worried about is when you 
pass an RC'd type as an argument by value, for example, you make 
a copy. To be safe the compiler should wrap the original in an 
inc/dec cycle for the duration of the call. But this is a waste 
if there's no risk of reassignment, if you're just mutating the 
original data, or if the type isn't even an RC'd type but has 
some other kind of destructor. My guess was that `@destroy` could 
help the compiler elide unnecessary cycles this way.

If you always pass by reference (e.g. `ref`), you're sending the 
original, rather than copying it. This needs no wrapping 
therefore, since any reassignment will affect the original. What 
good would ownership do in that case? Any normal copying will 
increase the refcount anyway.

I'm starting to think that refcounting is precisely the opposite 
of ownership, useful only for when its *impossible* to track 
ownership easily. Otherwise why would you need a refcount?

What would be really interesting is a combined system, where the 
compiler detects the ownership properties of any given variable, 
and automatically decides whether it needs to be refcounted or 
not. There could be a built-in template in the runtime, e.g. a 
`_refCounted(T)`, which must be a perfect drop-in replacement for 
a regular `T` in all cases -- difficult, yes, but interesting to 
imagine at least -- which the compiler would swap in at its 
discretion. Obviously a huge flight of fancy, given that D is not 
in the habit of altering the basic type of a variable based on 
how it used... but it would be very efficient if it worked.

Do you agree that refcounting and ownership oppose each other, 
that refcounting only makes sense when ownership is impossible? 
That refcounting is a runtime mechanism for tracking precisely 
what a compile time ownership system can't? In other words, what 
problems does ownership solve, and how?


More information about the Digitalmars-d mailing list