Possible Duplicate:
Why does my destructor appear to be called more often than the constructor?
I have a static sCounter and int id to order my instances with id’s.
When grouping them in a vector, this works fine.. ID’s are setted corrrectly:
Task t("1st Task");
Task t2("2nd Task");
Task t3("3rd Task");
std::vector<Task> myTasks;
myTasks.push_back(t);
myTasks.push_back(t2);
myTasks.push_back(t3);
task number one has ID 0, the second one: ID 1 and the third one ID 2.
However, if I do this:
std::vector<Task> myTasks;
myTasks.push_back(
Task("First Task"));
myTasks.push_back(
Task("Second Task"));
myTasks.push_back(
Task("Third Task"));
The static sCount values starts giving strange results:
the first one gets ID 1, the second also ID 1, and the third gets ID 0.
Why does creating object like this mess with the static counter?
The sCounter gets increased on the constructor, and decreased on the destructor:
int Task::sCount = 0;
Task::Task(std::string text) {
this->setText(text);
this->setStatus(1);
time_t now = time(0);
timestamp = *localtime(&now);
std::cout << "Count from " << sCount;
sCount++;
std::cout << " to --> " << sCount << "\n";
this->setID(); // set the current sCount to ID
}
Task::~Task() {
--sCount;
}
sCounter is a private static int: static int sCount;
In the second case, each Task instance passed to push_back is a temporary variable. This means that its destructor is called once the call to push_back is complete. The destructor then decrements the counter before the next Task is created.
Although the Task is copied into the vector (so the data exists elsewhere in memory), the implicit copy constructor that std::vector uses for this does not increment the counter.