in principle:
1. The class type of C++ is a value type, which means that when a class object is instantiated, memory is allocated on the stack.
In this way, if the class type is defined like this
class A
{
public:
int i;
A a;
}
It will fall into an infinite loop, because when instantiating an object of A, A needs to calculate the memory space occupied by such an object based on the member type (the data members are determined based on the type, and the code of the member function is stored in the exe To map to memory, just use a pointer to point to the memory address, and add some class description information, but sizeof does not display the memory usage of this part of the description information). When encountering an object a of its own type, it calculates the data used by a. Memory space, and a is of type A, so repeat.
So in C++
Can contain pointers of its own type (often used in linked lists)
class A
{
public:
int i;
A*pa;
}
The memory space occupied by a pointer variable is easy to determine. The number of machine words in length indicates how much space the pointer variable occupies.
2. The class type in C# is a reference type, which is essentially a pointer.
Therefore, all class objects in C# themselves are 4 bytes (32-bit machine) and contain a memory address, which points to the heap memory space.
class A
{
public int i;
public A a;
}
A object = new A();
The object itself occupies 4 bytes of memory and stores the heap memory address. The size of this memory is 8 bytes (int 4 bytes, a is also four bytes). When member a is instantiated, the content of a is not null. , stores another address in the heap memory, pointing to an 8-byte memory space.
Because we can determine how much memory space an object of A occupies (4 bytes, all C# class objects occupy 4 bytes, in a 32-bit machine), we can define
-