Copy or reference when accessing row vectors of Ei

2019-07-20 21:39发布

问题:

I'm working with code that uses the Eigen matrix library. I've noticed that all through that code, there are accessors as follows:

RowVector3f V(size_t vertex_index) const
{
    return mymatrix.row(vertex_index);
}

Wouldn't it be better to use an accessor that returns a const ref? Is that possible with Eigen? Or maybe just return the pointer to internal float to the row-begin and cast it to a vector (of course assuming matching row-major layout)?

回答1:

In Eigen, mymatrix.row(vertex_index) returns a Block (assuming mymatrix is a Matrix3f). A Block object is essentially a pointer to the original data. In your case, this proxy is copied into a RowVector3f. Fortunately, for such small fixed size objects, the compiler will easily optimize away this extra copy. So I'd not bother.

In a more general case, I'd rewrite the V method to return a MatrixXf::RowXpr (which is a proper typedef to Block<...>).



回答2:

I don't know this library, but I did use that techinique, namely, return objects, and return them by value and not by reference. This is for security - you can't change the original data when you return a portion of it by value.

Also, using objects instead of pointers to data make the code more syntax-friendly and high level.