通过使用运营商的QUOT声明值类型;新" [英] Declaring value types by using operator "new"

查看:127
本文介绍了通过使用运营商的QUOT声明值类型;新"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据说值类型存储在堆栈中。但是,当我们用声明值类型,会发生什么新的
为例




int类型的;




存储在堆栈中,但




INT b =新INT();




在哪里b的存储?堆或叠?它混淆了我。这就像一个参考,但它是一个值类型。


解决方案

有人说,值类型存储在堆栈




这是经常说,但是这显然是错误的。当你一个阵列,100个整数,做那些整数住在栈上,或堆?



这是存储的寿命有事情做与该类型的想法存储是完全错误的。正确的说法是,已知寿命短的值类型的变量可以从短期储存的,当你这样说的话听起来很明显的分配。



请确保你清楚这一点:这是完全错误的 INT I; 的意思是栈上分配我。它的意思是因为我分配存储空间;如果该存储寿命已知是短则它可以在短期内店铺进行分配。否则,被分配在长期的商店。




但是,当我们宣布新的值类型会发生什么?




您所想,新使新的存储被分配了堆。它不是。想想新意为获取存储,然后调用构造函数。



一类型获得的存储是始终在堆上因为类数据的寿命是不知道要短。对于一个数值类型获得的存储记录为堆栈上,然后该值的复制的最终目的地,这可能是栈或堆中的。但该分配及复印件可复制省略如果编译器能确定它是安全的这样做。



下面有一些文章,这将有助于:



http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx



的http://博客.msdn.com / b / ericlippert /存档/ 2010/10/11 /揭穿-的又一次神话有关 - 值types.aspx


It is said that value types are stored in stack. But what happens when we declare a value type with new? For example

int a;

is stored in stack, but

int b=new int();

Where does b is stored? Heap or stack? It's confuses me. It's like a reference, but it's a value type.

解决方案

It is said that value types are stored in stack

This is said frequently but it is obviously false. When you make an array with 100 ints, do those ints live on the stack, or the heap?

The idea that the lifetime of storage has something to do with the type of the storage is simply false. The correct statement is that variables of value type that are of known short lifetime can be allocated from short-term storage, which sounds pretty obvious when you put it that way.

Make sure you're clear on that: it is simply false that int i; means "allocate i on the stack". It means "allocate storage for i"; if that storage lifetime is known to be short then it can be allocated on the short term store. Otherwise it is allocated on the long-term store.

But what happens when we declare a value type with new?

You're thinking that "new" causes new storage to be allocated off the heap. It does not. Think of "new" as meaning "obtain storage and then invoke a constructor".

The storage obtained for a class type is always on the heap because the lifetime of the class data is not known to be short. The storage obtained for a value type is documented as being on the stack, and then the value is copied to its final destination, which might be on the stack or the heap. However that allocation and copy can be copy-elided if the compiler can determine that it is safe to do so.

Here are some articles that will help:

http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx

http://blogs.msdn.com/b/ericlippert/archive/2010/10/11/debunking-another-myth-about-value-types.aspx

这篇关于通过使用运营商的QUOT声明值类型;新"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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