How to free memory of c++ WinRT value structs

我怕爱的太早我们不能终老 提交于 2019-12-12 13:17:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!