将H5 :: CompType初始化为类的静态成员

问题描述:

我正在使用库HDF5以二进制保存。将H5 :: CompType初始化为类的静态成员

我想要一些用户定义的“全局”数据类型,我在开始时初始化,然后在需要时使用它。

例如,我想为“Vector”(它只是一个结构,其组件是两个双打:x,y)定义一个复合类型。

我想实现这个想法在下面的方法(我基本上都是从这个答案了:https://*.com/a/27088552/4746978

// inside Vector.h 
struct Vector 
{ 
    double x; 
    double y; 
} 


// inside Hdf5types.h 
#include "Vector.h" 
class Hdf5types 
{ 

private: 
    static H5::CompType m_vectorType; 

public: 
    static const H5::CompType& getVectorType(); 

}; 


//inside Hdf5types.cpp 
#include "Hdf5types.h" 
H5::CompType Hdf5types::m_vectorType = Hdf5types::getVectorType(); 

const H5::CompType& Hdf5types::getVectorType() 
{ 
    struct Initializer { 
      Initializer() { 
       m_vectorType = H5::CompType(sizeof(Vector)); 
       m_vectorType.insertMember("x", HOFFSET(Vector, x), H5::PredType::NATIVE_DOUBLE); 
       m_vectorType.insertMember("y", HOFFSET(Vector, y), H5::PredType::NATIVE_DOUBLE); 
      } 
    }; 
    static Initializer ListInitializationGuard; 
    return m_vectorType; 
} 

代码编译,但我在运行时得到一个问题,因为一个异常被抛出:

异常抛出:读取访问冲突。

this-> was nullptr。

“this”是指在HDF5库中称为“IdComponent”的对象。 我不知道如何继续,因为我没有时间深入图书馆。也许有人知道HDF5有解决方案!

您在程序启动过程中太早分配值。所以你静态分配是调用HDF5库功能,它尚未实例化。所以SIGSEV。

你可以做什么会是这样的:

// inside Hdf5types.h 
#include <H5Cpp.h> 
#include "Vector.h" 

class Hdf5types{ 

private: 
    static H5::CompType* m_vectorType; 

public: 
    static const H5::CompType& getVectorType(); 

    Hdf5types(); 

}; 

#include "hdf5types.h" 

H5::CompType* Hdf5types::m_vectorType = nullptr; 

Hdf5types::Hdf5types() {} 

const H5::CompType& Hdf5types::getVectorType() { 
    if (m_vectorType == nullptr) { 
    struct Initializer { 
     Initializer() { 
     m_vectorType = new H5::CompType(sizeof(Vector)); 
     m_vectorType->insertMember("x", HOFFSET(Vector, x), H5::PredType::NATIVE_DOUBLE); 
     m_vectorType->insertMember("y", HOFFSET(Vector, y), H5::PredType::NATIVE_DOUBLE); 
     } 
    }; 
    static Initializer ListInitializationGuard; 
    } 
    return *m_vectorType; 
} 

这会懒洋洋地初始化m_vectorType

+1

谢谢。这解决了我的问题! 我想我必须释放分配的内存吗?我不确定是否在析构函数中使用它,因为我没有创建任何Hdf5对象。你怎么看? – Turms

+0

valgrind并没有说明对象没有被释放。但是你绝对应该添加一个析构函数。 –