Simon Baynes: Web Development

Copying Structures

Once you start using structures you need to understand pointers. This essentially is that if you set a variable equal to a structure you do not create a copy but in fact a reference (or alias). This means that if you change either of them you will change them both.

<cfscript>
    stDemo = structNew();
    stDemo.sName = "Simon";
    stDemo.nAge = 27;

    stNew = stDemo;
    stNew.nAge = 28;

    // now check the result of this output
    writeOutput(stDemo.nAge);
</cfscript>

So as you can see this does not perform as you would expect. The way to prevent this is to use the duplicate() function.

<cfscript>
    stDemo = structNew();
    stDemo.sName = "Simon";
    stDemo.nAge = 27;

    stNew = duplicate(stDemo);
    stNew.nAge = 28;

    // now check the result of this output
    writeOutput(stDemo.nAge);
</cfscript>
By Simon Baynes