Recently, on the Nashville ColdFusion User Group list, a thread about copying variables from one session to another session spawned the question: "Just what is a deep copy?" In order to answer this question we need to understand some fundamental things regarding the behavior of Arrays and Structures in ColdFusion.

When Arrays are copied, all complex variables (structures, nested arrays, etc.) are copied by reference. This means the new array holds a reference to the complex variable in the original array. If in the new array you change a property of one of these complex variables, the original array will also receive the change. To eliminate this behavior the developer needs to perform a "deep copy" of the original array. This is done using ColdFusion's Duplicate() function.

variables.firstArray = ArrayNew(1);
variables.firstArray[1] = "Aaron";
variables.firstArray[2] = "West";
variables.secondArray = Duplicate(variables.firstArray);
Structures, on the other hand, behave a little different. All top-level keys, values, and arrays are copied by value whereas all nested structures are copied by reference. Using the syntax thisStruct = thatStruct or thisStruct = StructCopy(thatStruct) will copy, by reference, the values in thatStruct. To perform a deep copy of the original structure - and create a brand new structure - you use the Duplicate() function.

variables.firstStruct = StructNew();
variables.firstStruct.firstName = "Aaron";
variables.firstStruct.lastName = "West";
variables.secondStruct = Duplicate(variables.firstStruct);

In order to demonstrate this behavior I put some more concrete examples together. You can download them using the link below. Make sure that you run these examples on a fully patched CFMX 6.1 server. Otherwise, you may not experience correct results.

Click here to download the "deep copy" examples.

Aaron West's Gravatar
About this post:

This entry was posted by Aaron West on November 16, 2004 at 12:38 PM. It was filed in the following categories: ColdFusion. It has been viewed 2578 times and has 0 comments.

0 Responses to Defining "deep copy" and ColdFusion's Duplicate Function