void foo()
{
int aaa = 0; //值类型,aaa在Stack上分配(SUB ESP,XX)
int* paaa = new int[123]; //引用类型,paaa在Heap上分配,HeapAlloc(GetProcessHeap()...)
foo2(&aaa); //【引用】值类型aaa
}->函数退出,aaa从栈上销毁,paaa依然存在在进程堆中。
void foo2(int* paaa)
{
*paaa = 123;
}void foo(int* pa)
{
beginthread(&new_thread...,pa); //启动新线程操作指针pa
}
void new_thread(int* pa)
{
Sleep(1000); //新线程睡眠1秒
if (*pa == 123) //判断pa指针的内容是123
OutputDebugStringA("OK.");
}void exec1()
{
int pa = 123;
foo(&pa);
}void exec2()
{
int* pa = (int*)malloc(sizeof(int));
*pa = 123;
foo(pa);
}void foo()
{
int aa = 123; //aa直接指向123,编译器通过ESP指针进行间接访问
int* paa = (int*)malloc(sizeof(int)); //paa指向堆上的一块内存
*paa = 123; //编译器使用直接指针访问
}void foo()
{
int* pa = new int[123]; //引用类型
pa[0] = 123;
int aa = *pa; //aa是栈上的值类型,从堆上把数据进行memcpy,UnBox
}void foo()
{
int aa = 123; //值类型
int* pa = new int[123]; //引用类型
pa[0] = aa; //堆上的引用类型数据改了
aa = 456; //栈上的值类型变了,但堆上的数据可不会同步变,这可不是WPF的数据绑定,哈哈
}private void Form1_Load(object sender, EventArgs e)
{
int aaa = 123; //Value Type
IntPtr paaa = System.Runtime.InteropServices.Marshal.AllocHGlobal(sizeof(int)); //Ref Type
System.Runtime.InteropServices.Marshal.WriteInt32(paaa,aaa); //Box
aaa = System.Runtime.InteropServices.Marshal.ReadInt32(paaa); //UnBox
}void foo()
{
int aaa = 123;
System.Diagnostics.Debug.WriteLine(((aaa as ValueType) as object).ToString());
}private bool IsValueType(object o)
{
return o is ValueType ? true : false;
}
private void Form1_Load(object sender, EventArgs e)
{
int aaa = 123;
System.Diagnostics.Debug.WriteLine(IsValueType(aaa).ToString()); //True
var bc = new Form();
System.Diagnostics.Debug.WriteLine(IsValueType(bc).ToString()); //False
}原文:http://blog.csdn.net/a1875566250/article/details/39454649