static member inside of class in vector

I am testing a static variable inside of a class. I want it to count the number of instances of the class. Then I want to put my class into an array.

At the creation of my class inside of the array, the count should go up. Then when I destroy an element of the array, the count should go down. I have a destructor that reduces the size of count. If I remove the destructor count goes up fine, but I want the destructor to reduce count. Seems like my destructor is being called when I did not mean for it to.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream> 
#include <vector>

using namespace std;


class myClass {
	int id;
public:
	static int count;

	int getCount() {
		return count;
	}
	//constructor
	myClass () {
		count++;
	}
	
	~myClass() {;
		count--;
	}

};

//initializer
int myClass::count = 0;


int main() {
	
	vector<myClass> myVec;

	for (int i = 0; i < 3; i++) {
		myVec.resize(myVec.size() + 1);
	}

	cout << "The size of my vector: " << myVec.size() << endl;
	cout << myVec[0].getCount() << endl;

	myVec.pop_back();
	
	cout << "The size of my vector: " << myVec.size() << endl;
	cout << myVec[0].getCount() << endl;

	cin.get();
	return 0;

}
Last edited on
You should implement the copy and move constructors.
ok so are you saying that when the resize() function gets called, it is using a copy constructor and the default copy constructor does not use count++ to increase count value? So if I define a copy constructor for resize to use then the problem will be solved?
Thank you master helios!

Your subtle insight was nothing short of mad genius!

Thanks to you I had a most pleasurable c++ experience.
Problem solved!
Yes. You should define both copy and move constructors, as std::vector::resize() may use either.
I am new to the concept of move constructor. How do you do that?
In your case, the move constructor will be the same as the copy constructor, only with a different signature.

1
2
3
myClass::myClass(myClass &&){
    count++;
}
Thanks.
Topic archived. No new replies allowed.