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

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

问题描述

我的印象是,在 C# 中,结构元素在堆栈上分配,因此在从创建它们的方法返回时消失.但是如果我将 struct-values 放在一个列表中并返回它会发生什么?元素存活.结构实例有时会在堆上分配吗?

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;
  }
}

代码打印 0, 1, 2

code printing 0, 1, 2

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

推荐答案

首先,阅读 Eric Lippert 在 堆栈是一个实现细节.跟随它价值类型的真相.至于你的具体问题

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天全站免登陆