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

How to free memory of c++ WinRT value structs


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

I declared the struct

// Custom struct
public value struct PlayerData
{
    Platform::String^ Name;
    int Number;
    double ScoringAverage;
};

like

auto playerdata = PlayerData();
playerdata.Name = ref new String("Bla");
return playerdata;

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


Solution

  • When a value struct is assigned to another variable, its members are copied, so that both variables have their own copy of the data (see Value classes and structs (C++/CX)). The same rule applies, when returning a value struct from a function.

    In your code you have playerdata, an object of type PlayerData with automatic storage duration. The return statement makes a copy of playerdata (including the Platform::String^ member), and returns this copy to the caller. After that, playerdata goes out of scope, and is automatically destroyed.

    In other words: The code you posted works as expected. You do not have to explicitly free any memory.