C#new出来的结构体内存分配

https://blog.csdn.net/c1sdn19/article/details/88402893
https://www.cnblogs.com/TivonStone/archive/2011/11/24/2261090.html
https://jonskeet.uk/csharp/memory.html 这篇文章已经讲解的很清楚了。
https://stackoverflow.com/questions/4853213/are-structs-always-stack-allocated-or-sometimes-heap-allocated
在这里插入图片描述

总结:
1、结构体作为单独的类型出现的时候,new或者是声明,都是分配在栈上的。
2、结构体作为引用类型的成员时,内存分配在堆上。

struct PairOfInts
{
    static int counter = 0;

    public int a;
    public int b;

    internal PairOfInts(int x, int y)
    {
        a = x;
        b = y;
        counter++;
    }
}

class Test
{
    PairOfInts pair;
    string name;

    Test(PairOfInts p, string s, int x)
    {
        pair = p;
        name = s;
        pair.a += x;
    }

    static void Main()
    {
        PairOfInts z = new PairOfInts(1, 2); 
        Test t1 = new Test(z, "first", 1);
        Test t2 = new Test(z, "second", 2);
        Test t3 = null;
        Test t4 = t1;
        // XXX
    }
}

1、z栈上
2、t1本身在栈上,t1所指的内容在堆上,t1的成员pair在堆上。
3、t2本身在栈上,t2所指的内容在堆上,t2的成员pair在堆上。
4、t3本身在栈上,t3指向的内容为null。
5、t4本身在栈上,t4和t1所指向的内容为同一块堆上的内存。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值