struct vs. class containers (was: Re: dcollections 1.0 and 2.0a beta released)

Steven Schveighoffer schveiguy at yahoo.com
Mon May 24 08:58:18 PDT 2010


On Sun, 23 May 2010 17:36:52 -0400, Andrei Alexandrescu  
<SeeWebsiteForEmail at erdani.org> wrote:

> I've thought for a very long time about the class vs. struct choice in a  
> container, and I came to a startling conclusion: it (almost) doesn't  
> matter. Could be either, and the tradeoffs involved are nonessential.  
> Here they are:
>
> 1. Using a class makes implementing members easier because there's no  
> need to do work through an additional member. With a struct, you need a  
> pimpl approach. For example:
>
> struct Array {
>      struct Impl {
>          ...
>      }
>      Impl * impl;
>      ...
>      @property length() const { return impl->length; }
>      ...
> }
>
> 2. struct gives you more power in managing collection's own memory, as  
> long as the collection doesn't escape item addresses or other addresses  
> of internal handles. So all other things being equal, struct has a net  
> advantage.

Yes, but most containers are node-based, so as long as you use structs for  
nodes, you are generally in control of the bulk of allocation  
(dcollections does this).

>
> 3. The creation syntaxes are different. For Phobos, I suggest adding a  
> simple function make() to std.algorithm. make!T(a, b, c) returns a newly  
> constructed object T by invoking the constructor with arguments a, b,  
> and c. That way we can make client code virtually agnostic of the  
> class/struct choice for a container.
>

Classes have builtin object monitors.  But you could handle that via a  
struct as well.  The language support wouldn't be there though.

> That's it. Otherwise, one could use either to build a container. Let me  
> note that I have reached the conclusion that containers should be at  
> best reference types, with a meta-constructor Value!(C) that takes a  
> container C and makes it into a value type.

The thing that classes really give you is the language support.  Structs  
need to be hand-crafted to support the same syntax.  Classes are enforced  
as always being reference types and always being on the heap.  The  
Value!(C) is questionable because creating the head of a container on the  
stack leads to easily escaped stack references.

But yeah, a struct as a 'smart pointer' could work, as long as you don't  
'auto-create' like AA's do.

>
> It seems Steve took the weekend off.

My son's 2nd birthday party was Saturday, and I had visitors, sorry :)  I  
did some responses, but at some point if you want to remain married, you  
have to pay attention to your family.

-Steve


More information about the Digitalmars-d-announce mailing list