0

I am slightly confused about the following code

void foo() {

  std::list<A*> list;

  for (int i = 0; i < 3; i ++) {
    A a = A(i);
    list.push_back(&a);
  }

  for (Iterator it = list.begin(); it != list.end(); it++) {
     std::cout <<  (*it);
  }
}

which prints out three times the object a with constructor argument 2, i.e. the last object constructed in the loop.

What am I doing wrong here?

4
  • 1
    That's not how you push into a list. Even if it was - you're pushing references to objects that won't exist outside of the first loop iteration Commented Jun 19, 2014 at 17:36
  • @Leeor sorry that was a typo Commented Jun 19, 2014 at 17:37
  • Second part still applies - you run over the same object with each iteration, so you have a good chance to see the last value (and that the 3 pointers will be the same), but don't trust undefined behavior Commented Jun 19, 2014 at 17:39
  • @Leeor coming from java, I always fall into this trap Commented Jun 19, 2014 at 17:43

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Or use a std::shared_ptr<A> or std::unique_ptr<A> instead of a raw pointer.
3

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.