c++boostboost-foreach

Get a pointer to the current BOOST_FOREACH element


Given the following simple code:

list<MyClass> m_listOfOBjects;
....
MyClass* ptrToMyClass;
BOOST_FOREACH(MyClass object, m_listOfObjects)
{
      ptrToMyClass = &object
}

My question, is does the ptrToMyClass now points to a temporal object or to the real object in the list. If it's the first case is there some way to get a pointer to the object in the list instead of the temporal variable created by the BOOST_FOREACH loop?


Solution

  • As the declaration MyClass object, object will be a copy, not the object in the list. Try to use reference,

    BOOST_FOREACH(MyClass& object, m_listOfObjects)
    {
          ptrToMyClass = &object;
    }