a static struct array to keep track of all structs

362 views Asked by At

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.

1

There are 1 answers

3
Robin Hartland On BEST ANSWER

When you define MyStruct MyStruct::*AllStructs;, all you are doing is allocating memory for one single pointer to a MyStruct 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 static std::vector instead to manage the memory allocation for the MyStruct. Simple as this:

#include <vector>
#include <iostream>
class MyStruct{
public:
static std::vector<MyStruct*> AllStructs;
MyStruct(){AllStructs.push_back(this);}
};
std::vector<MyStruct*> MyStruct::AllStructs;


int main() {
    MyStruct ms;
    MyStruct ms2;
    std::cout << MyStruct::AllStructs.size() << std::endl;

}

Hope that helps!