内存分配:堆栈VS堆? [英] Memory allocation: Stack vs Heap?

查看:424
本文介绍了内存分配:堆栈VS堆?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我越来越混淆栈之间的内存分配基础VS堆,按照标准清晰度(事大家说),所有的值类型将得到分配到一个堆栈和引用类型将进入堆。
现在考虑下面的例子:

I am getting confuse with memory allocation basics between Stack vs Heap, as per the standard definition (things which everybody says), all value types will get allocated onto a Stack and reference types will go into the Heap.
now consider the following example:

class MyClass
{
    int myInt = 0;

    string myString = "Something";
}

class Program
{
    static void Main(string[] args)
    {
       MyClass m = new MyClass();
    }
}

现在如何分配的内存将在C#中发生?​​
将在MyClass的(即米)的物体将被完全分配给堆即INT敏和string MyString中既会去堆?
或该对象将被分为两部分,将被分配到两者的存储器位置,即栈和堆?

now how does the memory allocation will happen in c#?
will the object of MyClass (i.e. m) will be completely allocated to the Heap i.e. int myInt and string myString both will go to heap?
or the object will be divided into two parts and will be allocated to both of the memory locations i.e. Stack and Heap?

推荐答案

M 是在堆中分配,这包括。其中,基本类型(和结构)被分配在堆栈上的情况是在方法调用,它分配空间在堆栈中的局部变量(因为它的速度更快)。例如:

m is allocated on the heap, and that includes myInt. The situations where primitive types (and structs) are allocated on the stack is during method invocation, which allocates room for local variables on the stack (because it's faster). For example:

class MyClass
{
    int myInt = 0;

    string myString = "Something";

    void Foo(int x, int y) {
       int rv = x + y + myInt;
       myInt = 2^rv;
    }
}

RV X 将全部在栈。 是某处堆上(而且必须通过访问指针)。

rv, x, y will all be on the stack. myInt is somewhere on the heap (and must be access via the this pointer).

这篇关于内存分配:堆栈VS堆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆