I am trying to create a program that can hold as many objects as the user wants. The objects will hold how many times it member method, 'data' has been called, and also will have a random age assigned to it. If all goes well the method 'printData' should print the values to the screen that are determined in 'data'.
I wasn't sure if I should use a vector of object pointers or not so I have commented out the code with pointers. The difference seems to be when I have vector<Zoo*> ZooPtrVex; constructors will be called but no copy constructors and when I have vector<Zoo> zooVex; I call way too many copy constructors!
#include<iostream>
#include<vector>
#include "Zoo.h"
usingnamespace std;
int main()
{
int index = 1;
vector<Zoo*> ZooPtrVex;
Zoo* zooPtr =new Zoo[index];
//I want 5 objects so I will use for loop
for (int i = 0; i < 5; i++)
{
ZooPtrVex.push_back(zooPtr->pData(zooPtr));
index++;
zooPtr = new Zoo[index+1];
}
for (int i = 0; i < 5; i++)
{
ZooPtrVex[i]->printData();
}
delete[] zooPtr;
system("Pause");
return 0;
}
How to I minimize the constructor count?! I've managed to call like 25 of them even though I only want 5 objects! LOL
$ ./a.out
Construct Calls 1
Begin loop
Adding 0 to the vector
copy Construct Calls 1
Adding 1 to the vector
copy Construct Calls 2
copy Construct Calls 3
Adding 2 to the vector
copy Construct Calls 4
copy Construct Calls 5
copy Construct Calls 6
Adding 3 to the vector
copy Construct Calls 7
Adding 4 to the vector
copy Construct Calls 8
copy Construct Calls 9
copy Construct Calls 10
copy Construct Calls 11
copy Construct Calls 12
data Call Count 5
0
data Call Count 5
0
data Call Count 5
0
data Call Count 5
0
data Call Count 5
0
Summary
Ctor=1
CCtor=12
Data=5
A lot of the excess copy ctors come about when the vector gets resized internally - where it allocates a new storage area and copies across all the old entries to the new larger space.
You could reduce this by doing say
zooVex.reserve(10);