-1

I have the following code segment:

std::list<reply_t> l = m[index];
for (std::list<reply_t>::iterator it = l.begin(); it != l.end(); it++) {
    // do something
}

and

std::list<reply_t> *l = &(m[index]);
for (std::list<reply_t>::iterator it = l->begin(); it != l->end(); it++) {
    // do something
}

m is just a map with int index and list as values, ie std:map<int, std::list<reply_t> >.

The two versions ONLY differ in how the list is being referred to, ie one by pointer one by object. Everything else in my code is exactly identical. HOWEVER, when I run with these two versions, version 1 consistently fails tests and version 2 consistently succeeds. The code is used in a multi threaded context, if that helps.

I'm new to c++ and this is just completely bizarre to me. Anyone with an possible explanation?

jet
  • 698
  • 6
  • 12
  • How exactly does version 1 fail? How/what are you testing? – Irfy Feb 18 '12 at 02:03
  • 1
    What is reply_t? Does it follow the [rule of three](http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29)? Does it make sense to copy it? – Irfy Feb 18 '12 at 02:06
  • @Irfy, didn't know about the rule of three. thanks for pointing that out! – jet Feb 18 '12 at 02:14

1 Answers1

6

The two examples differ in that the first creates a copy of the list returned by m[index], then iterates over that copy.

To match the second version, you need to use a reference to the list. Try this instead:

std::list<reply_t>& l = m[index]; // notice extra '&' character.
André Caron
  • 44,541
  • 12
  • 67
  • 125
  • so c++ automatically copies an object for assignment? and you need to explicitly specify reference by address for any assignment? – jet Feb 18 '12 at 02:13
  • 1
    C++ does not "automatically" copy objects. The statement in your code explicitly requests a copy by initializing a new `std::list` object with a reference to an existing instance (e.g. the one stored at `m[index]`). If you're confused about the syntax, I suggest you read a [good C++ book](http://stackoverflow.com/questions/388242). – André Caron Feb 18 '12 at 02:16