jeudi 25 octobre 2018

Global objects and static members of class

I made a class which has a static member in it. Every time an object is created I want to add the pointer to this object in the static member.

class A
{
public: 
    A(const int pin) { A::channels.push_back(this); };

    static std::vector<A*> channels;
}

In the main.cpp I want to declare the object. However, when I declare and initialize as a global variable it doesn't seem to work:

A a1{ 1 };
A a2{ 2 };

int main() {
    std::cout << "Vector size: " << A::channels.size() << std::endl;
}

The above mentioned code doesn't seem to work. In the constructor of the object I see the vector being filled. The output is 0 in the above case.

For the 2 code samples below, however, does seem to work.

Sample 1:

A *a1;
A *a2;

int main() {
    a1 = new A{ 1 };
    a2 = new A{ 2 };

    std::cout << "Vector size: " << A::channels.size() << std::endl;
} 

Sample 2:

int main() {
    A a1{ 1 };
    A a2{ 2 };

    std::cout << "Vector size: " << A::channels.size() << std::endl;
}

In the above 2 cases it prints 2, which is what I expected.

Can anyone help me explain what i'm doing wrong, or what I'm missing. I'm guessing it has to do something with the scope of the objects but I can't seem to reason why the first example doesn't work.

Edit: I didn't add the destructor for the class since I didn't think it is relevant for this question.

Aucun commentaire:

Enregistrer un commentaire