Is there any way to use a ref class in a value type class?

I've just got into to managed c++. I've created a class called Player which type is value. Now within this class I need to use some sort of dynamic array. I've tried using System List but the visual studio gives me an error that I can not use a ref class in a value class. What is this error? What can I use?

using namespace System;
using namespace Collections;
using namespace Generic;

public value class Player
{
     // other codes

     List<int> MyItems  // Gives error : Can not use ref class

     // other codes
};

Answers


This is not a problem, a value class can contain any reference type reference. What you cannot do is arbitrarily omit the ^ hat, the member must be a reference as demanded by .NET since the object is always allocated on the heap. The compile error you get is a bit clumsy, perhaps. This compiles fine:

public value class Player {
    List<int>^ list;             // Note: ^ required.
};

In this case, I don't think you need to use a value class here. You can read up on them if you wish (Value Class in C++/CLI, C++/CLI: Value Class Types)

Instead, just make Player a reference type. This is what most user classes should be. The main difference is that you allocate with gcnew, and the garbage collector will do the cleanup. You also need to use the ^ to indicate a reference. In your code, this is missing for the List member.

public ref class Player
{
    // other codes

    List<int>^ MyItems;

    // other codes
};

void use()
{
    Player^ p = gcnew Player();
    //use p, but make sure MyItems gets allocated with `gcnew`
    //somewhere as well!
}

Need Your Help

process id ist different between getpid und Top command linux

linux top-command

programm write current process id in file with function getpid() exemple 1100, but wenn command top run, i becomme process id 1101!!!!! why