此管理对象存储在哪里? [英] Where is this managed object stored?

查看:245
本文介绍了此管理对象存储在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

value class ValBase
{
  public:
    int a;
};

ref class RefBase
{
public:
     int a;
};

int main(array<System::String ^> ^args)
{

RefBase^ RefBase1 = gcnew RefBase; //LEGAL. Ref type Managed Obj created on CLR heap.
ValBase^ ValBase1 = gcnew ValBase; //LEGAL. Value type Managed Obj created on CLR heap.

RefBase* RefBase2 = new RefBase;   //ILLEGAL: new cannot be used on Managed Ref Class
ValBase* ValBase2 = new ValBase;   //This compiles okay but where is this "Managed Object" stored ? CLR heap or Native heap ? 

}

在最后一次分配中,管理对象存储在哪里?我对C ++ CLI完全陌生。同样,值类型是否应该使用堆栈语义来提高代码效率,这是真的吗?即代替ValBase ^ ValBase1 = gcnew ValBase,我应该只使用ValBase ValBase1;

In the last assignment where is the managed object stored ? I am totally new to C++ CLI. Also, is it true that value types should use stack semantics to make code efficient ? i.e instead of ValBase^ ValBase1 = gcnew ValBase, I should just use ValBase ValBase1;

推荐答案

只需添加引用类型的成员值类型:

Just add a member of a reference type to the value type:

value class ValBase
{
  public:
      String^ s;
      int a;
};

...
ValBase* = new ValBase;

编译器会告诉您确切的存储位置:

And the compiler tells you exactly where it is stored:


错误C3255:'ValBase':无法在本机堆上动态分配此值类型对象

error C3255: 'ValBase' : cannot dynamically allocate this value type object on native heap

语义很简单,毕竟您可以将值类型存储在堆栈中。如果它可以放在堆栈上,那么它也可以放在本机堆上。只要它不包含垃圾收集器必须找到的对象。这就是为什么C3255在那里的原因。正是由于这个原因,.NET框架中存在值类型,将值存储在堆栈中很便宜,并且使代码高效。

The semantics are simple enough, after all you can store a value type on the stack. If it can go on the stack then it can go on the native heap as well. As long as it doesn't contain objects that need to be found back by the garbage collector anyway. Which is why C3255 is there. Value types exist in the .NET framework for this very reason, storing stuff on the stack is cheap and makes code efficient.

但是仅仅因为它是可能的将其存储在本机堆上并不能使其完全有用。对于 ValBase ^ ValBase1 = gcnew ValBase; ,也是如此,它将 boxed 值存储在托管堆上。嵌入System :: Object中的值的副本。装箱非常有用,因为它可以假装值类型从Object继承。但这并不便宜,从来没有任何理由你不想做。

But just because it is possible to store it on the native heap doesn't make it exactly useful to do so. Same is true for ValBase^ ValBase1 = gcnew ValBase;, that stores a boxed value on the managed heap. A copy of the value embedded in a System::Object. Boxing is very useful because it allows pretending that value types inherit from Object. But it isn't cheap, never something you'd want to do for no good reason.

这篇关于此管理对象存储在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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