views:

64

answers:

2

I'm trying to use a std::list in my objective-c program and having run-time issues.

I have (edit for brevity)

 #import <list>

 ...

 @interface Foo {
    std::list<Bar *> *myList;
 }

 ...

 @implementation Foo

 -(void)loopList {

   myList = new std::list<Bar *>;

   for (std::list<Bar *>::iterator ii; ii != myList->end(); ++ii) 
   {
      // Do nothing here
   }
 }

Everything compiles fine, but I get a EXC_BAD_ACCESS while executing the for loop. I'm not doing anything with the contents, just looping though them (for now).

I'd use NSMultableArray, but I need to quickly insert and remove elements while I'm iterating, which is not possible. Also, I'd like to use the stl for speed issues.

I have my files set to sourcecode.cpp.objcpp.

Thanks in advance.

+1  A: 

I don't know about objective C, but in C++ you need to tell the iterator which list instance it is iterating over:

for (std::list<Bar *>::iterator ii = myList->begin(); 
                  ii != myList->end(); ++ii) 
anon
+3  A: 

This line:

for (std::list<Bar *>::iterator ii; ii != myList->end(); ++ii) 

Needs to become:

for (std::list<Bar *>::iterator ii = myList->begin(); ii != myList->end(); ++ii) 

In your version, ii is never assigned a value, so it has nothing to iterate over. Based on the code you posted it's not clear why, but because of this you later attempt to dereference an invalid memory address and that's why you generate an exception (EXC_BAD_ACCESS).

benzado
myList is a pointer And ii is an iterator object, with a constructor, not just "random memory".
anon
Thanks, adding ii = myList->begin() solved the problem. Don't know why I missed that!
Roger Gilbrat
@Neil: being an iterator doesn't guarantee a constructor, and the existence of a constructor doesn't guarantee initialization of anything!
Potatoswatter
@Neil: `ii` just contains the value of whatever was on the stack in the place where it was allocated. It's not a valid object. Why else would he be getting `EXC_BAD_ACCESS` errors?
benzado
The C++ standard 12.1.9 says: "Default constructors are called implicitly to create class objects of static or automatic storage duration [...] defined without an initializer.".
dreamlax
@benzado: `ii` is not a pointer, it is a stack-allocated class object, and its default constructor will be called implicitly.
dreamlax
I've updated my answer, in case the down-voters would like to reconsider.
benzado