Any good site or explanation on what is a ref class
and when to declare a class to be a "ref class"?
The explanation on msdn wasn't enough for me,
base_type(optional)
A base type. A ref class or ref struct can inherit from zero or more managed interfaces and zero or one ref types. A value class or value struct can only inherit from zero or more managed interfaces.
ref
The
ref
keyword tells the compiler that the class or structure will be allocated on the heap and a reference to it will be passed to functions or stored in class members. Thevalue
keyword tells the compiler that all of the data in the class or structure is passed to functions or stored in members.
A ref class can contain public , protected , and private function members; only public and protected members are emitted into metadata. Nested classes and ref classes are permitted but cannot be public . Public fields are not allowed; public data members must be declared as properties.
Managed classes A managed class is a class that is garbage collected, means you don't have to delete it after using it. All that's managed for you by the common language runtime. In MC++ we create managed classes using the __gc keyword as shown below.
gcnew is an operator, just like the new operator, except you don't need to delete anything created with it; it's garbage collected. You use gcnew for creating . Net managed types, and new for creating unmanaged types.
What is a ref struct? Well, a ref struct is basically a struct that can only live on the stack. Now a common misconception is that since classes are reference types, those live on the heap and structs are value types and those live on the stack.
Basically, a ref class
is a CLR class. It's the equivalent of class
in C#.
This creates a reference type managed by the CLR. If you want to make a class that's usable from C#, you'd normally create a ref class
. (ref struct
, by the way, does exactly the same thing, but with C++'s standard class vs. struct default accessibility rules.)
Also, just for reference - in order to make a value type (struct
in C#), you'd use value class
or value struct
.
A good explanation of many of these new keywords is Herb Sutter's post on C++/CLI Keywords. This is a useful reference if you're new to C++/CLI, but have a solid C++ background.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With