Re: Problem with pointers and iterators

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Victor Bazarov

    Re: Problem with pointers and iterators

    Griff Johns wrote:
    Hi, if I have the following code:
    class MyObject
    {
    public:
    MyObject() {};
    ~MyObject() {};
    >
    int x;
    >
    }
    >
    class MyObjectList : public std::vector<MyO bject{};
    >
    void Foo(MyObject* obj)
    {
    // Do something with obj->x
    >
    }
    >
    If I loop through it like this:
    >
    MyObjectList list;
    // stuff list with objects
    >
    MyObjectList::i terator it;
    for (it = list.begin(); it != list.end(); ++it) {
    // I used to be able to do this:
    MyObject* p_obj = it;
    Foo(p_obj);
    >
    // Or this
    Foo(it);
    >
    }
    >
    But now the error I get is 'cannot convert parameter 1 from
    'std::vector<_T y>::iterator' to 'MyObject *'
    >
    This is after migrating a project from vc6.0 to vc7.1, but I think that
    the issue lies with the language standards(?). So why does this happen
    now, and how do I resolve it?
    You need to *fix it*. Iterators are *not* pointers. If you need to
    gain access to the address of the object to which the iterator points,
    you need to dereference the iterator and then take the address of the
    result:

    MyObject *p_obj = &*it;

    or

    Foo(&*it);

    Dereferencing yields a reference, taking the address of a reference
    yields a pointer.

    V
    --
    Please remove capital 'A's when replying by e-mail
    I do not respond to top-posted replies, please don't ask
Working...