N
news.chi.sbcglobal.net
Hi.
I am a little confused about the difference between a "value class" and a
"ref class".
I have the following code sample that shows the definition of a value class
and of a ref class and each is instantiated twice - one on the stack and one
on the managed heap. I see no difference between the two, at least not in
the way they are used. Can someone explain the difference, please? Thank
you.
Jeff
ref class RefClass
{
public:
int x;
RefClass(int xx) { x = xx; }
};
value class ValClass
{
public:
int x;
ValClass(int xx) { x = xx; }
};
int main(array<System::String ^> ^args)
{
// create the value class
ValClass val(1);
// use the value class
Console::WriteLine("{0}", val.x);
// create a ref class
RefClass ref(1);
// use the ref class
Console::WriteLine("{0}", ref.x);
// create val on the managed heap
ValClass ^valHandle = gcnew ValClass(1);
// use it
Console::WriteLine("{0}", valHandle->x);
// create ref on the managed heap
RefClass ^refHandle = gcnew RefClass(1);
// use it
Console::WriteLine("{0}", refHandle->x);
return 0;
}
I am a little confused about the difference between a "value class" and a
"ref class".
I have the following code sample that shows the definition of a value class
and of a ref class and each is instantiated twice - one on the stack and one
on the managed heap. I see no difference between the two, at least not in
the way they are used. Can someone explain the difference, please? Thank
you.
Jeff
ref class RefClass
{
public:
int x;
RefClass(int xx) { x = xx; }
};
value class ValClass
{
public:
int x;
ValClass(int xx) { x = xx; }
};
int main(array<System::String ^> ^args)
{
// create the value class
ValClass val(1);
// use the value class
Console::WriteLine("{0}", val.x);
// create a ref class
RefClass ref(1);
// use the ref class
Console::WriteLine("{0}", ref.x);
// create val on the managed heap
ValClass ^valHandle = gcnew ValClass(1);
// use it
Console::WriteLine("{0}", valHandle->x);
// create ref on the managed heap
RefClass ^refHandle = gcnew RefClass(1);
// use it
Console::WriteLine("{0}", refHandle->x);
return 0;
}