mike mike - 1 month ago 10
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());
tmp.setZero();
while (v1_beg != v1_end) { tmp += *v1_beg++ * *v2_beg++; }

}


I know that passing
Eigen
types to functions can be a tricky business if one wants to avoid temporaries. The above solution seems to avoid temporaries (e.g. printing
&(*v_beg).data()
gives the correct memory address of the location in the external vector). However, due to the subtleties involved in passing pure
Eigen
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 (
*v1_beg
)?

Thanks for any comments!

Answer

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.