I have to create a struct, a static variable to keep track of how many structs are alive and also a list of all current structs. I'm having trouble creating this list and the appropriate constructor. So far I have
class MyStruct{
public:
static int i;
static MyStruct *AllStructs;
MyStruct(){i++; (AllStructs++)=this;} //error happens here
};
int MyStruct::i=0;
MyStruct MyStruct::*AllStructs;
int main(){...}
As you can see I tried to do it by creating a static array that gets added to as part of the constructor, but the compiler gives me an error: "lvalue required as left operand of assignment" in the place I indicated. It's not letting me assign new structs to my static array.
What am I doing wrong? Keep in mind pointers are the bane of my life so please explain it to me as you would to a small child. Thanks a lot.
When you define
MyStruct MyStruct::*AllStructs;
, all you are doing is allocating memory for one single pointer to aMyStruct
object, not actually creating space for an array of them. This array you want needs to have a valid memory location initialised for it to live in, where it can store its copy of all the pointers you want it to. That's likely to get messy though, so you should use a staticstd::vector
instead to manage the memory allocation for theMyStruct
. Simple as this:Hope that helps!