pass-by-ref semantics for structs (was Deque impl.)

Steven Schveighoffer schveiguy at yahoo.com
Thu Jan 31 10:59:19 PST 2013


On Thu, 31 Jan 2013 11:17:14 -0500, Andrei Alexandrescu  
<SeeWebsiteForEmail at erdani.org> wrote:

> On 1/31/13 11:00 AM, Steven Schveighoffer wrote:
>> On Thu, 31 Jan 2013 10:40:15 -0500, Andrei Alexandrescu
>> <SeeWebsiteForEmail at erdani.org> wrote:
>>> It has a destructor.
>>
>> One which is not called if allocated on the heap.
>
> That is correct. My point was that with structs we get to implement  
> full-fledged reference counting for containers.

But that won't work if the struct is on the heap.  You will leak the  
memory.

Not only that, but if the container uses the GC to allocate nodes, calling  
the destructor during the GC cycle would be a bad thing.

> Reference counting makes a lot of sense for containers. They inherently  
> own their internals, don't have cycles, and are massive enough to make  
> pass by value effectively an anti-pattern (as it is for C++). At the  
> same time memory reclamation is of high interest. Reference counting is  
> really the sweet spot for containers.

Reference counting makes a lot of sense for any reference type.  Including  
classes.

I think your point is that we can do reference counting with structs, and  
we can't with classes.  I think:

a) you can do reference counting with both (at the moment, this requires a  
wrapper struct for the class)
b) structs that depend on destruction to free their memory do not work  
with the current runtime implementation.

>> It's possible to make a class reference that is destroyed when going out
>> of scope. Then you have the option, heap destroyed or stack destroyed.
>>
>> Not possible with structs (at least for now).
>
> I don't understand this. Is it about the deprecated meaning of scope?

It means, classes have a mechanism for destruction via the heap (GC) or  
via the stack (scope, or whatever currently replaces scope (Scoped? I  
can't remember) ).

Structs by default are easily destroyed from the stack, but lack the  
fundamental cogs to get GC-based destruction.

In other words, you can't put a reference-counted struct on the heap, it  
won't work correctly (the destructor won't get called).  This is not to  
say this can't be fixed, but if we are talking about current  
implementation limitations, classes are superior in how they can be used.

-Steve


More information about the Digitalmars-d mailing list