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 = "Aaron";
variables.firstArray = "West";
variables.secondArray = Duplicate(variables.firstArray);
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.
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 1974 times and has 0 comments.