Passing handle object to C++ leads to reference leak?

Viewed 136

I've come across this issue while debugging a simple for-loop where the iteration time would grow overtime. The issue seems to stem from the fact that passing a handle object to a C++ MEX function extends the lifetime of the handle until the end of the script.

Here is a minimum example to reproduce the issue.

First, the class simply let us track when the object gets deleted:

classdef Foo < handle
methods
  function this = Foo()
  end
  function delete(this)
    disp("DELETE FOO");
  end
end
end

Then, the C++-MEX function does nothing:

#include "mex.hpp"
#include "mexAdapter.hpp"
class MexFunction : public matlab::mex::Function
{
public:
  void operator()(matlab::mex::ArgumentList /*outputs*/, matlab::mex::ArgumentList /*inputs*/) override
  {
  }
};

Compile this (work_with_Foo.cpp) with:

>> mex work_with_Foo.cpp

Finally, the testing script:

index = 0;
while index ~= 3
  v = Foo();
  clear v;
  index = index + 1;
end
disp("End of regular loop");
index = 0;
while index ~= 3
  v = Foo();
  work_with_Foo(v); % pass the handle to the C++ MEX function
  clear v;
  index = index + 1;
end
disp("End of work_with_Foo loop");

Which provides the output:

DELETE FOO
DELETE FOO
DELETE FOO
End of regular loop
End of work_with_Foo loop
DELETE FOO
DELETE FOO
DELETE FOO

Actually, if you insert more work after the second loop you can see that the handles are not deleted before the script ends.

Is this a known issue and is there any way to work around it?

The same behavior has been confirmed on Matlab R2018a on Linux and Matlab R2019a, R2018b on Windows.

0 Answers
Related