These days to learn C #, see the value types inside and reference types, such as the structure is a value type, the class is a reference type, and then immediately think of C + + classes, then C + + What kind of class is it, haha, suddenly a little confused, the internet search is really a lot of small partners have fainted in, today summed up the C # and C + + in the difference between the value type and the reference type.
In fact, the fundamental difference between a value type and a reference type in C # is that the variable contains the data on which memory interval, the value type is directly contained in the stack, and the reference type is referenced indirectly in the heap, for example, C # The following syntax is required for instantiating a class in:
Class name = Newclass ();
It is easy to see that the class is allocated space in the heap, and then let name point to the allocated space.
So there are no value types and reference types in C + +, you know that C + + does not specifically distinguish between value types and reference types,C + + The reference type in C+ + is different from the reference type in C # ,which refers to the alias of a variable, regardless of which memory area the variable is in. For example, the following two reference methods:
One
Int B = 12;
int* A = &b;
int* &c = A;
Two
int* B = newint;
Int* & A =b;
As can be seen from the above, the reference inC + + is actually an alias for a variable, and the internal implementation of the reference is actually implemented by pointers. But variables of reference types in C # store references to their data (objects), while variables of value types directly contain their data. The difference is still very big.
So the class in C + + is the equivalent of what's in C # , and we can see where the classes in C + + are allocated in which memory area, see the following two ways to declare a class:
The first kind of direct declaration, the class is allocated on the stack:
classa{};
Aa;
The second way through New allocates memory, classes are allocated in the heap:
classa{};
A*a = new A ();
we can almost tell by the above two ways. C + + in relation to C # The difference between a middle value type and a reference type is that the first kind is declared in the stack, which is actually the corresponding C # the second type of exhaustion is declaring the class in the heap, which is actually the corresponding C # the reference type in the.
at hand, I hope to give the same beginner's little friends some hints, where there are mistakes hope everyone points out, thank you.
Value types and reference types in C #