问题
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?
回答1:
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.
回答2:
The playerdata struct is created on the stack; 'new' was not called. It was not created on the heap, so there is no memory that needs to be freed.
来源:https://stackoverflow.com/questions/35781419/how-to-free-memory-of-c-winrt-value-structs