Copying objects vs. primitive type

Jarrett Billingsley kb3ctd2 at yahoo.com
Sat Jun 30 21:23:09 PDT 2007


"muffles" <sgtmuffles at myrealbox.com> wrote in message 
news:f66tbd$14o1$1 at digitalmars.com...
> How should I go about accounting for this difference in behavior?

Do you necessarily need to?  What if your list is a list of objects which 
can't really be duplicated, such as objects which represent open files?  Or 
what if you want to be able to dup the list and have the new list reference 
the same class instances?

If you want to be a bit more flexible, you could auto-detect if the element 
type has a .dup method, and use it if it does.  Here's a possible example.

// The AutoDup parameter can be set to false in order to override the
// automatic discovery of .dup methods; if it's false, when duplicated
// and the element is a reference type, the new list will reference the
// same data.
class LinkedList(T, bool AutoDup = true)
{
    struct Node
    {
        T data;
        Node* next;
    }

    ....

    LinkedList!(T, AutoDup) dup()
    {
        auto ret = new LinkedList!(T, AutoDup);

        ...

        // This use of is() is checking to see if the element type
        // has a dup method.  This'll work for arrays too.
        static if(AutoDup && is(T.dup))
        {
            for(Node* n = mHead; n !is null; n = n.next)
                ret.addNode(n.data.dup);
        }
        else
        {
            // No dup-ing
            for(Node* n = mHead; n !is null; n = n.next)
                ret.addNode(n.data);
        }

        return ret;
    }
} 




More information about the Digitalmars-d-learn mailing list