I am slightly confused about the following code
void foo() {
std::list list;
for (int i = 0; i < 3; i ++) {
A a = A(i);
list.push_
The variable a
is local to the first for loop, so it is destroyed at the end of each iteration of the loop. This means that after the loop finishes, all three pointers in list
point to objects that no longer exist. Dereferencing those pointers causes undefined behaviour.
If you'd like to worry less about remembering to de-allocate the allocated memory (and have a nicer less error prone code) you should use unique_ptr or shared_ptr (read about them and shoose whichever fits your needs best).
Here is a small example (notice how the elements in the vector get deleted when the vector goes out of scope):
cout<<"Scope begins"<<endl;
{
vector< unique_ptr<A> > v;
for (int i=0; i<5; ++i){
v.push_back(unique_ptr<A>(new A(i)) );
}
}
cout<<"Scope ends"<<endl;
Live demo here.
You have a list of dangling pointers.
for (int i = 0; i < 3; i ++) {
A a = A(i);
list(&a);
}
In each iteration, this loop creates an object of type A
, which is immediately destroyed when the iteration completes. So the contents of the list are undefined. You would need something like this:
for (int i = 0; i < 3; i ++) {
A* a = new A(i);
list(a);
}
...but don't forget to delete them all in another loop when you're done with the list.