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

C++ 将H5::CompType初始化为类的静态成员,c++,hdf5,static-members,C++,Hdf5,Static Members,我正在使用库HDF5以二进制形式保存 我希望有一些用户定义的全局数据类型,我在开始时初始化,然后在需要时使用它 例如,我想为一个向量定义一个复合类型,它只是一个结构,其组件是两个双精度:x,y 我试着用下面的方法来实现这个想法,我基本上是从这个答案中得到的: 代码可以编译,但在运行时引发异常时遇到问题: 引发异常:读取访问冲突 这是nullptr 这是指HDF5库中称为IdComponent的对象。 我不知道该怎么做,因为我没有时间深入图书馆。也许有人谁知道HDF5有一个解决方案 在程序启动过程

我正在使用库HDF5以二进制形式保存

我希望有一些用户定义的全局数据类型,我在开始时初始化,然后在需要时使用它

例如,我想为一个向量定义一个复合类型,它只是一个结构,其组件是两个双精度:x,y

我试着用下面的方法来实现这个想法,我基本上是从这个答案中得到的:

代码可以编译,但在运行时引发异常时遇到问题:

引发异常:读取访问冲突

这是nullptr

这是指HDF5库中称为IdComponent的对象。
我不知道该怎么做,因为我没有时间深入图书馆。也许有人谁知道HDF5有一个解决方案

在程序启动过程中过早赋值。所以,静态分配调用的是HDF5库功能,它还没有被实例化。所以西格夫

你能做的是:

// 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_矢量类型。

谢谢。这解决了我的问题!我想我必须释放分配的内存,对吗?我不确定在析构函数中这样做是否有效,因为我没有创建任何Hdf5对象。你怎么看?瓦尔格林并不是在抱怨这个物体没有被释放。但是你应该添加一个析构函数。
// 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;
}