4

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?

Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158
Toine db
  • 709
  • 7
  • 25
  • @πάντα ῥεῖ FYI, WinRT = [c++-cx], not [c++-cli] – Lucas Trzesniewski Mar 03 '16 at 21:26
  • @LucasTrzesniewski sorry for the mixup. Any comments how to free memory from objects that cross the boundry between the windows runtime component and a C# project? (like my PlayerData) – Toine db Mar 04 '16 at 08:00
  • no worries, I just pointed out to another editor that he added the wrong tag. I myself have no experience with WinRT and only saw your question because of the C++/CLI tag, so I'm afraid I can't help you. – Lucas Trzesniewski Mar 04 '16 at 08:46

2 Answers2

3

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.

IInspectable
  • 46,945
  • 8
  • 85
  • 181
  • and andy, many thanks for the answers, very clear. BUT it turned out I needed classes instead of a struct, to get them From runtime component to my c# project. Do i need to free memory (classes) that I created in the runtime component that got back to the c# project? like: https://github.com/cmusphinx/pocketsphinx-wp-demo/blob/master/PocketSphinxRntComp/SpeechRecognizer.h#L32 – Toine db Mar 21 '16 at 10:01
  • @Toinedb: If you have another question, you should click the [Ask Question](http://stackoverflow.com/questions/ask) button. – IInspectable Mar 21 '16 at 10:56
  • OK, will do that. Thanks again – Toine db Mar 21 '16 at 11:44
1

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.

Andy Rich
  • 1,942
  • 10
  • 14