使用Eigen庫和stl容器時遇到問題
在程式中使用了這樣的容器
std::vector<Eigen::Matrix4f> p;
由於Eigen自身分配空間方法與stl空間分配的問題,在執行push_back()操作時,有時會彈出如下的錯誤資訊,並導致程式崩潰。
Assertion failed: (reinterpret_cast<size_t>(array) & 0xf) == 0 && "this assertion is explained here: " "http://eigen.tuxfamily.org/dox-devel/group__TopicUnalignedArrayAssert.html" " **** READ THIS WEB PAGE !!! ****"
根據提示訪問了http://eigen.tuxfamily.org/dox-devel/group__TopicUnalignedArrayAssert.html網頁,網頁中顯示可能的原因如下:
Cause 1: Structures having Eigen objects as members
If you have code like this,
class Foo { //... //... }; //... Foo *foo = new Foo;Cause 2: STL Containers or manual memory allocation
If you use STL Containers such as std::vector, std::map, ..., with Eigen objects, or with classes containing Eigen objects, like this,
The same issue will be exhibited by any classes/functions by-passing operator new to allocate memory, that is, by performing custom memory allocation followed by calls to the placement new operator. This is for instance typically the case of std::make_shared
std::allocate_shared
for
which is the solution is to use an aligned allocator as detailed in the solution
for STL containers.
Cause 3: Passing Eigen objects by value
If some function in your code is getting an Eigen object passed by value, like this,
Cause 4: Compiler making a wrong assumption on stack alignment (for instance GCC on Windows)
This is a must-read for people using GCC on Windows (like MinGW or TDM-GCC). If you have this assertion failure in an innocent function declaring a local variable like this:
然後跳轉到網頁http://eigen.tuxfamily.org/dox-devel/group__TopicStlContainers.html,找到了正確的使用方法:The case of std::vector
The situation with std::vector was even worse (explanation below) so we had to specialize it for the Eigen::aligned_allocator type. In practice you must use the Eigen::aligned_allocator (not another aligned allocator), and #include <Eigen/StdVector>.
Here is an example:
#include<Eigen/StdVector> /* ... */ std::vector<Eigen::Vector4f,Eigen::aligned_allocator<Eigen::Vector4f> >