Skip to main content
Inspiring
April 9, 2008
Question

Returning local method variables from a CFC

  • April 9, 2008
  • 2 replies
  • 474 views
I am wondering if someone can help me understand why I should or should not be concerned about returning local variables from a called component - at least for datatypes that are passed by reference rather than value. I am currently refraining from doing this, since it appears that the calling routine would receive back a pointer to memory that the CFC method would have released back to the operating system upon its completion.

I've attached an example of what I'm talking about. When the code is finished running, I expect mystruct will be a pointer to the foo structure, which may or may not have been released to the operating system after mycfcmethod completes.

So far I have been dealing with this safely, I believe, by always returning a duplicated version of the results, such as Duplicate(foo). I would like to avoid this extra overhead if it is unnecessary. Possibly CF knows to hold onto any memory that is referenced elsewhere, or possibly it doesn't.

Any insights would be appreciated.
This topic has been closed for replies.

2 replies

April 9, 2008
Memory in your calling templates is reserved for a structure when you call mycfcmethod. That is why you specify the signature Structure mycfcmethod(). So, that returned structure will remain available during the scope of the calling template's use of the structure.

Honestly, I am not sure if this means that CF duplicates the structure or if a pointer keeps the initial memory from being collected. It would seem to be the latter. Regardless, your sample code should work. You should not find that structure disappears unexpectedly.
Inspiring
April 9, 2008
Rimshot wrote:
> Any insights would be appreciated.
>
> Calling Code:
> <cfset mystruct = mycfcmethod()>
>
> ------------------------
> Hypothetical CFC Method:
> <cffunction name="mycfcmethod" output="no" returntype="struct" access="public">
> <cfset var foo = StructNew()>
> <cfset foo["color"] = "Red">
> <cfset foo["size"] = "large">
> <cfreturn foo>
> </cffunction>
>

You did not show the use of duplicate() in this example, but it is not
necessary.

Buried somewhere deep on the documentation is the description that
ColdFusion will pass simple values by reference and complex values by
pointer. So you will end up with 'mystruct' pointing to the same memory
defined for 'foo'.
Inspiring
April 9, 2008
Thank you for your response Ian.

I am a bit confused by your answer, though, in that a structure is a complex variable, and therefore would point back to the released foo memory. As such a separate copy of the structure would need to be returned...no? Your comment indicated that Duplicate would not be needed.

Sorry for my lack of clarity regarding my use of Duplicate. I am using it in my return statemet within the method: