我终于遇到了这里描述的烦人的问题:https://eigen.tuxfamily.org/dox/group__TopicStlContainers.html
我有一个包含多个特征固定大小矩阵的结构,并且我想将结构的多个实例存储在 std::vector 中。显然,“这些问题仅出现在固定大小的可矢量化特征类型和具有此类特征对象作为成员的结构中。”适用。然而,它仅描述了如何使用直接收集特征对象的向量来解决问题,而不是使用包含特征实例的结构来解决问题。
目前我的问题是这样的:
struct MyStruct{
EIGEN_MAKE_ALIGNED_OPERATOR_NEW //Don't know if this applies here
Eigen::Matrix<double, 4, 4> A;
// several more instances and stuff here
MyStruct ( ...) // constructor taking several arguments, but only running an initilization list for some members
// no destructor defined / implemented !
// no methods!
}
//
MyStruct instanceStruct( .. constructing .. );
instanceStruct.A = someAssigment() ;
// this type of 'instancing' before i push it into the vector is necessary ...
std::vector<MyStruct> myVector;
myVector.push_back( std::move( instanceStruct ) ); // gdb tells me that here we run into a SIGSEGV
造成问题的原因是什么?谢谢你!
从 C++17 开始
标准容器使用的默认分配器需要遵守对齐方式,任何存储持续时间的变量也是如此(*)。因此,在这种情况下,您的代码应该开箱即用,因为 Eigen 会在需要时指定对齐方式。
(*) 有caveats though:
从 C++11 开始
您唯一应该担心的事情是通过 new 或默认分配器获得的动态存储持续时间的变量(请参阅P0035r4更多细节)。
现在,Eigen 通过提供 EIGEN_MAKE_ALIGNED_OPERATOR_NEW 和
本征::对齐分配器:
struct MyStruct{
EIGEN_MAKE_ALIGNED_OPERATOR_NEW // this will make new MyStruct to work
//...
// this will make vector (or any other allocator-aware container) to work
std::vector<MyStruct,Eigen::aligned_allocator<MyStruct> >
请注意,与官方文档所述相反,您可以在 C++11 中使用任何对齐的分配器,因此无需#include<Eigen/StdVector>
(如果在 C++11 之前的模式下编译,或者您的编译器不完全支持 c++11 对齐语义,则必须包含它)。
或者,您可以禁用矢量化(请参阅 Eigen 宏文档以了解如何操作)或仅通过 new 分配可矢量化矩阵:
struct MyStructImpl{
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
// vectorizable matrices ...
};
struct MyStruct
{
MyStructImpl* aligned_data_; // possibly a unique_ptr<MyStructImpl>
// copy-move-assign accordingly ...
// non-vectorizable matrices and other data ...
};
std::vector<MyStruct> v; // ok !
这将花费你的堆分配和更少的内存局部性,但会更便宜地移动 MyStruct。因此,它可能会更快或更慢,具体取决于您的用例。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)