mike mike - 6 months ago 37
C++ Question

Pass std::iterator pointing to a vector of Eigen types

I have a large

std::vector<Eigen::Array<float, Eigen::Dynamic, 1>>
sitting somewhere in memory. I can pass iterators to this vector to a function, like below:

typedef std::vector<Eigen::Array<float, Eigen::Dyanamic, 1>>::iterator ArrayIterator;

void MyFunction(ArrayIterator v1_beg, ArrayIterator v1_end,
ArrayIterator v2_beg, ArrayIterator v2_end) {

Eigen::Array<float, Eigen::Dynamic, 1> tmp(*v1_beg.size());
while (v1_beg != v1_end) { tmp += *v1_beg++ * *v2_beg++; }


I know that passing
types to functions can be a tricky business if one wants to avoid temporaries. The above solution seems to avoid temporaries (e.g. printing
gives the correct memory address of the location in the external vector). However, due to the subtleties involved in passing pure
types, it almost seems "too easy". My question is: can I be confident that an approach like above will not result in the creation of temporaries? Or might the temporary be invoked when I dereference (

Thanks for any comments!


In your example *v1_beg will return a reference to a Eigen::Array<float, Eigen::Dynamic, 1> (which is the same as Eigen::ArrayXf, btw), no Eigen code is invoked up to that place. The actual Eigen code then calls (semi pseudo code):

ArrayXf::operator+=(operator*(const ArrayXf&, const ArrayXf&))

which indeed works without temporaries.