Search code examples
matlabmatlab-coder

Matlab Code Generation for Handle Classes Reallocated in a Loop


I am running into some behavior in Matlab Coder that I don't completely understand. To simplify, here's a short example that exhibits the behavior. If I have a handle class defined as:

classdef somehandleclass < handle %#codegen

properties
    something
end

methods
    function obj = somehandleclass(initval)
        obj.something = initval;
    end
end

end

and a short function to use it:

function result = runsomehandleclass %#codegen

obj = somehandleclass(0);
for i=1:6
    obj = somehandleclass(i);
end

result = obj.something;

end

...then I build the runsomehandleclass function with a simple build script:

cfg = coder.config('mex');
cfg.GenerateReport = true;
codegen -config cfg runsomehandleclass

I get the following error:

??? Unsupported allocation. An allocated handle object escapes the loop. Error in ==> runsomehandleclass Line: 5 Column: 11

I understand the text of the error, clearly I'm creating new instances of somehandleclass each time through the loop. My question is: why should that be an error? In this simple example it is trivial to work around this, but the problem occurs in a much larger code base where deep in another function a handle class is reinstantiated with substantially different settings. I can (and have) worked around this, but the new solution is much less elegant. In reality, there's no leak here, as handle classes are supposed to be deleted when their handle is overwritten.

If I remove the inheritance from handle and make the class a value class, the error goes away and the mex compiles as expected, however in my actual application, I do wish to have a handle class.

Is this expected behavior by the compiler? Also, is there a workaround, for instance is there some way to explicitly delete obj before I construct a new instance into obj?


Solution

  • See here, it's your case.

    In obj = somehandleclass(i);, obj, which was initialized outside of the loop, referred to a somehandleclass object created inside the loop. In other words, use value class if you want to use it inside a loop.