我在Matlab Coder中遇到了一些我不完全理解的行为。为简化起见,这是展示行为的简短示例。如果我有一个句柄类定义为:
classdef somehandleclass < handle %#codegen
properties
something
end
methods
function obj = somehandleclass(initval)
obj.something = initval;
end
end
end
以及使用它的简短函数:
function result = runsomehandleclass %#codegen
obj = somehandleclass(0);
for i=1:6
obj = somehandleclass(i);
end
result = obj.something;
end
...然后我用一个简单的构建脚本构建runsomehandleclass
函数:
cfg = coder.config('mex');
cfg.GenerateReport = true;
codegen -config cfg runsomehandleclass
我收到以下错误:
???不支持的分配。分配的句柄对象会转义循环。 ==&gt;中的错误runsomehandleclass线:5列:11
我理解错误的文字,显然我每次都要在循环中创建somehandleclass
的新实例。我的问题是:为什么这应该是一个错误?在这个简单的例子中,解决这个问题是微不足道的,但是问题出现在一个更大的代码库中,其中深度在另一个函数中,句柄类被重新实例化,具有截然不同的设置。我可以(并且已经)解决这个问题,但新的解决方案不那么优雅。实际上,这里没有泄漏,因为当句柄被覆盖时应该删除句柄类。
如果我从handle
删除继承并使该类成为值类,则错误消失并且mex按预期编译,但是在我的实际应用程序中,我希望有一个句柄类。
这是编译器的预期行为吗?另外,是否有解决方法,例如,在我将obj
构建新实例之前,是否有某种方法可以显式删除obj
?
答案 0 :(得分:1)
请参阅here,这是您的情况。
在obj = somehandleclass(i);
中,在循环外部初始化的obj
引用了在循环内创建的somehandleclass
对象。换句话说,如果要在循环中使用它,请使用值类。