Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterator vs. Reference vs. Pointer [closed]

Tags:

c++

I have a class that spawns an arbitrary number of worker object that compute their results into a std::vector. I'm going to remove some of the worker objects at certain points but I'd like to keep their results in a certain ordering only known to the class that spawned them. Thus I'm providing the vectors for the output in the class A.

I have (IMO) three options: I could either have pointers to the vectors, references or iterators as members. While the iterator option has certain draw backs (The iterator could be incremented.) I'm unsure if pointers or references are clearer. I feel references are better because they can't be NULL and a cruncher would require the presence of a vector.

What I'm most unsure about is the validity of the references. Will they be invalidated by some operations on the std::list< std::vector<int> >? Are those operations the same as invalidating the iterators of std::list? Is there another approach I don't see right now? Also the coupling to a container doesn't feel right: I force a specific container to the Cruncher class.

Code provided for clarity:

#include <list>
#include <vector>
#include <boost/ptr_container/ptr_list.hpp>

class Cruncher {
  std::vector<int>* numPointer;
  std::vector<int>& numRef;
  std::list< std::vector<int> >::iterator numIterator;
public:
  Cruncher(std::vector<int>*);
  Cruncher(std::vector<int>&);
  Cruncher(std::list< std::vector<int> >::iterator);
};

class A {
  std::list< std::vector<int> > container;
  boost::ptr_list< std::vector<int> > container2;
  std::vector<Cruncher> cruncherList;
};
like image 205
pmr Avatar asked Mar 01 '10 19:03

pmr


1 Answers

If an iterator is invalidated, it would also invalidate a pointer/reference that the iterator was converted into. If you have this:

std::vector<T>::iterator it = ...;
T *p = &(*it);
T &r = *p;

if the iterator is invalidated (for example a call to push_back can invalidate all existing vector iterators), the pointer and the reference will also be invalidated.

From the standard 23.2.4.2/5 (vector capacity):

Notes: Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence.

The same general principal holds for std::list. If an iterator is invalidated, the pointers and references the iterator is converted into are also invalidated.

The difference between std::list and std::vector is what causes iterator invalidation. A std::list iterator is valid as long as you don't remove the element it is referring to. So where as std::vector<>::push_back can invalidate an iterator, std::list<>::push_back cannot.

like image 135
R Samuel Klatchko Avatar answered Oct 05 '22 15:10

R Samuel Klatchko