是结构体总是堆栈中分配或有时堆分配? [英] Are Structs always stack allocated or sometimes heap allocated?

查看:451
本文介绍了是结构体总是堆栈中分配或有时堆分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是IM pression的,在C#中,结构元素被分配在堆栈上,从而在创建它们的方法返回时消失。但是,如果我把结构值列表中并返回该怎么办呢?元素生存。 有时在堆上分配结构实例?

 内部结构海虹之彩
{
  公众诠释我;
}内部类StruTry
{
  公开名单<海虹之彩>获取(INT最大值)
  {
    变种L =新的List<海虹之彩>();
    的for(int i = 0; I<最大;我++)
      l.Add(新海虹之彩{I = I});    返回升;
  }
}

code印花0,1,2

  [测试]
公共无效T()
{
  。VAR LL =新StruTry()获取(3);
  的foreach(在LL VAR STRU)
    Console.WriteLine(*+ stru.i);
}


解决方案

首先,阅读这篇文章从埃里克利珀的<一个href=\"http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx\">The栈是一个实现细节。与约值类型的真相
关于你提到的具体问题。


  

有时在堆上分配结构实例?


是的,他们有时在堆上分配。有很多时候,他们可以在堆中分配的例子。如果他们被装箱,或者如果他们在一个类中的字段,或者如果他们是一个数组的元素,或者如果他们已经关闭了,值类型的变量的值等。


  

但是,如果我把结构值列表中并返回该怎么办呢?元素生存。


您在想这个正确的方式,而这是在哪里值类型可能会被分配的要点之一。看到我提到了对真相的更多详细信息,值类型的第二个职位。但是,仅仅保持了协议栈是头脑的实现细节。关键外卖是,你真的不需要这个东西关心自己。你应该值类型和引用类型之间的语义差别有关。

I was of the impression that in C#, struct elements are allocated on the stack and thus disappear when returning from a method in which they were created. But what happens if I place the struct-values in a list and return that? The elements survives. Are struct instances sometimes allocated on the heap?

internal struct Stru
{
  public int i;
}

internal class StruTry
{
  public List<Stru> Get(int max)
  {
    var l = new List<Stru>();
    for (int i = 0; i < max; i++)
      l.Add(new Stru {i=i});

    return l;
  }
}

code printing 0, 1, 2

[Test]
public void T()
{
  var ll = new StruTry().Get(3);
  foreach (var stru in ll)
    Console.WriteLine("* "+ stru.i);
}

解决方案

First, read this post from Eric Lippert on The Stack is an Implementation Detail. Follow it with The Truth about Value Types. As for your specific question

Are struct instances sometimes allocated on the heap?

Yes, they are sometimes allocated on the heap. There are lots of examples of when they could be allocated on the heap. If they are boxed, or if they are fields in a class, or if they are elements of an array, or if they are the value of a variable of value type that has been closed over, etc.

But what happens if I place the struct-values in a list and return that? The elements survives.

You're thinking about this the right way, and this is one of the salient points on where a value type might be allocated. See the second post that I referred to on The Truth About Value Types for more details. But just keep The Stack is an Implementation Detail in mind. The key takeaway is that you really don't need to concern yourself with this stuff. You should be concerned with the semantic difference between value types and reference types.

这篇关于是结构体总是堆栈中分配或有时堆分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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