Search code examples
c#windows-runtimec++-cxwinrt-component

How to free memory of c++ WinRT classes created in the runtime component


Do I have to, and how can I, free memory from a class created in a Windows Runtime Component that has been returned to a managed C# project?

This question concerns Classes instead of structs like How to free memory of c++ WinRT value structs

The following scenario occurs

  1. C++\Runtime component Method is raised from C# project
  2. C++ class is created (a single class with a collection of other c++ classes)
  3. C++ class is returned
  4. C# project works with the data

I want to be sure the following classes wont create memory leaks: https://github.com/cmusphinx/pocketsphinx-wp-demo/blob/master/PocketSphinxRntComp/SpeechRecognizer.h#L32

I'm (still) new with freeing memory and haven't got a clue how and when to free this. Anyone?


Solution

  • All ref classes are reference-counted and will automatically be freed when there are no more live references. Because .NET uses a garbage collector, the memory might not be freed right away.

    If you have circular references in your app or library then the reference count of the objects will never hit zero and the memory will not be reclaimed (.NET can deal with circular references if all the objects are managed, but not if they come from outside the managed world, like your C++ classes).

    Whether or not your C++ code has internal memory leaks is another question.