I feel there's a bit of a misunderstanding going on between C++ and me...
My problem is that I have a deque of pointers to a class, and create objects then add them to the deque in a for loop. However, the destructor is called on the object as soon as the loop quits.
Code:
#include <deque>
#include "stdio.h"
class Test {
private:
static int number;
int id;
public:
Test(void);
Test(const Test&);
~Test(void);
};
int Test::number = 0;
Test::Test(void){
id = ++number;
printf("Creating number %d\n",id);
}
Test::Test(const Test& old){
id = old.id;
printf("Copying number %d\n",id);
}
Test::~Test(void){
printf("Deleting number %d\n",id);
}
int main(void){
std::deque<Test*> myDeque;
int i;
for(i=0;i<5;i++){
printf("\ni is now %d\n",i);
Test temp;
myDeque.push_front(&temp);
}
printf("Out of loop\n\n");
return 0;
}
This prints:
Code:
i is now 0
Creating number 1
Deleting number 1
i is now 1
Creating number 2
Deleting number 2
i is now 2
Creating number 3
Deleting number 3
i is now 3
Creating number 4
Deleting number 4
i is now 4
Creating number 5
Deleting number 5
Out of loop
Now, if I change the deque from deque<Test*> to deque<Test> then it works fine - I get:
Code:
i is now 1
Creating number 1
Copying number 1
Deleting number 1
...
Out of loop
...
Deleting number 5
Deleting number 4
...
Deleting number 1
However, I can't do this with my actual code, because I am creating a deque of pointers to an abstract class, so it won't let me instantiate the class. (This is all so that I can take advantage of polymorphism, and call functions on a set of similar objects without worrying what type of object I'm dealing with).
So, I suppose my question is: what is the correct way to create that deque of pointers to the abstract class? I don't seem to be barking up the right tree currently.
Thanks in advance