Christian Nagel's OneNotes

.NET Training, Consulting, Coaching - C#, Web Services, Enterprise Services, ASP.NET, Whidbey, Longhorn and More!

Sponsors

Affiliations

Books I've written

INETA UG Leaders

My Blogroll

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

Posted: Feb 28 2005, 02:05 PM by CNagel | with 3 comment(s)
Filed under: ,

Comments

mike said:

thanks this explanation was i lookin for...

thanks

# October 30, 2007 6:32 AM

Miguel said:

Hello,

Thanks for this nice short article.  May I ask two 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 ?

Thanks and regards,

Miguel

# July 23, 2009 5:34 PM

Miguel said:

I have another question as well:

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).

BR,

Miguel.

# July 23, 2009 5:48 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)