別のライブラリからのデータに Eigen3 を使用したいと考えています。ggael による以前の回答は、キーワードEigen::Matrix
を使用して既存のデータを採用する方法を示しています。new
ただし、結果はまだデータの所有権を取得しているように見えるため、これは私にとって十分ではありません。Matrix
つまり、範囲外になるとデータが解放されます。data
つまり、元のライブラリによって最終的に削除された場合、これはクラッシャーです。
void crasher(double* data, size_t dim)
{
MatrixXd m;
new (&m) Map<MatrixXd>(data,dim,dim); // matrix adopts the passed data
m.setRandom(); cout<<m<<endl; // manipulation of the passed data via the Matrix interface
} // data deleted by m => potential problem in scope of function call
私は2つの回避策を考え出しました:
void nonCrasher1(double* data, size_t dim)
{
MatrixXd m; // semantically, a non-owning matrix
const Map<const MatrixXd> cache(m.data(),0,0); // cache the original „data” (in a const-correct way)
new (&m) Map<MatrixXd>(data,dim,dim); // matrix adopts the passed data
m.setRandom(); cout<<m<<endl; // manipulation of the passed data via the Matrix interface
new (&m) Map<const MatrixXd>(cache); // re-adopting the original data
} // original data deleted by m
が存在するため、これはかなり不便ですcache
。もう 1 つはこの問題から解放されています。
void nonCrasher2(double* data, size_t dim) // no need for caching
{
MatrixXd m; // semantically, a non-owning matrix
new (&m) Map<MatrixXd>(data,dim,dim); // matrix adopts the passed data
m.setRandom(); cout<<m<<endl; // manipulation of the passed data via the Matrix interface
new (&m) Map<MatrixXd>(nullptr,0,0); // adopting nullptr for subsequent deletion
} // nullptr „deleted” by m (what happens with original data [if any]?)
ただし、ここでは、元のデータで何が起こるかは不明ですm
(もしあれば、Eigen3 のドキュメントからは完全には明らかではありません)。
私の質問は、そのデータの所有権を解放する標準的な方法があるかどうかですEigen::Matrix
(自己割り当てまたは採用)。