INETA Europe - UK and Ireland
WSE 2.0 SP3 released

C++/CLI Value Types and Memory Location

With C++/CLI value types can be put on the stack, or on the native or managed heaps.

value class MyData
{
  property int Simple;
};

Declaring the variable locally, the object is put on the stack.

MyData d1;
d1.Simple = 11;

Using the pointer syntax, the object can be put on the native heap:

MyData* pd2 = new MyData();
pd2->Simple = 22;
delete pd2;

With the gcnew operator boxing and unboxing is done behind the scenes:

MyData^ d3 = gcnew MyData();
d3->Simple = 33;
delete d3;   // invokes Dispose

Christian

Comments

Feed You can follow this conversation by subscribing to the comment feed for this post.

Miguel

Hello, Thanks for this nice short article. May I ask the following questions ? 1. MyData^ d3 = gcnew MyData(); d3-Simple = 33; In this case, MyData is created on the managed heap - is this correct ? 2. Are ref classes always created on the managed heap (unless they are created as a local variable as you mentioned in one of your other articles) ? Or can they be created on the native heap ? 3. If Value classes can be allocated on the stack, on the managed heap or on the native heap and Ref Classes can be allocated on the stack or on the managed heap, then what is the purpose of having Value Classes and Ref Classes ? (i.e., I was thinking up to now that a Value Class is used when you want to put the class on the stack and a Ref class is used when you want to put the class on the managed heap. Maybe this thinking is completely wrong). Thanks and regards, Miguel

Christian

Miguel, 1. yes 2. ref classes are always created on the managed heap, never on the stack. Also if they are declared as local variable, they create created on the managed heap. 3. see 2. I hope this helps. Christian

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment

Your Information

(Name and email address are required. Email address will not be displayed with the comment.)