I know that value classes don't have an default constructor as the compiler initializes all elements in this class with zero. But arrays are in a value class are not initialized:
value class c_LocationVal
{
public:
double x, y, z;
c_LocationVal(double i_x, double i_y, double i_z) {x = i_x; y = i_y; z = i_z;}
};
typedef cli::array<c_LocationVal> arrloc;
value class c_Managed
{
public:
arrloc^ m_alocTest;
//c_Managed() { m_alocTest = gcnew arrloc(3); } --> not permitted
double funcManaged ()
{
return m_alocTest[0].x; --> error: Object reference not set to an instance of an object
}
};
I just could cheat and use:
c_Managed(int i) { m_alocTest = gcnew arrloc(3); }
but there must be another solution.
Can someone please tell me how to solve this?
A value class is always initialized with "null/0". So a managed reference in a value class will also always be initialized to "null". If you want to have a special initialization, then you only have the solution, you were pointing out: You need to create a special constructor which has some parameters to "initialize" the value class correctly.
The question is: Do you really need a value class which contains a managed reference??? Normally this should also be a
ref class
.Also, what happens, if the value class is copied? What should happen with the reference? It will also directly copied! Is this intended? The goal of a value class is to provide a "real" copy! In your case it will not "fully copied"...
Pleas re-think if a
value class
is the best solution for your data storage...