Structs Passed By Value (Copied) When Using “argumentCollection=”
July 7th, 2008 | by Shayne |In ColdFusion I often find myself questioning whether or not I should pass data around by reference or value. Unfortunately in ColdFusion it’s transparent to the programmer what’s going on. Sure there are many blog posts citing the basic rules of thumb, however it’s always nice to test things out - just to be sure.
I recently ran into a situation in which I assumed ColdFusion was passing a struct by reference to a method - however, I things weren’t working correctly so I wrote up a quick test script to check what was going on. What came out of it was - ColdFusion apparently copies structs when they’re passed using “argumentCollection=” as a named argument in a method call.
Below is an example, tested on ColdFusion 8.0.1
<!--- Our simple struct to test reference vs value ---> <cfset qux = StructNew() /> <cfset qux.bar = "quux" /> <!--- Dump the fresh qux struct, our control ---> <cfdump var="#qux#" label="beforeFoo" /> <!--- Run foo() pass qux as an argumentCollection ---> <cfset foo(argumentCollection=qux) /> <!--- Dump showing that qux was passed by value ---> <cfdump var="#qux#" label="afterFoo" /> <!--- Dump qux as a control for foo2 ---> <cfdump var="#qux#" label="beforeFoo2" /> <!--- Run foo2() passing qux in as an argument ---> <cfset foo2(qux) /> <!--- Dump showing qux was passed by reference ---> <cfdump var="#qux#" label="afterFoo2" /> <!--- Functions ---> <cffunction name="foo"> <cfargument name="bar" /> <cfset arguments.bar = "baz" /> <cfdump var="#arguments#" label="inFoo" /> </cffunction> <cffunction name="foo2"> <cfargument name="struct" /> <cfset arguments.struct.bar = "baz" /> <cfdump var="#arguments.struct#" label="inFoo2" /> </cffunction>
Tags: gotchas