gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:00:23 24 4
gpt4 key购买 nike

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

我想要某种用户定义的“全局”数据类型,我在开始时对其进行初始化,然后在需要时使用它。

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

我尝试通过以下方式实现这个想法(我基本上是从这个答案中得到的:https://stackoverflow.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;
}

代码可以编译,但我在运行时遇到了一个问题,因为抛出了异常:

Exception thrown: read access violation.

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

关于c++ - 将 H5::CompType 初始化为类的静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46170659/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com