使用变量作为全局变量
Using a variable as global
我正在使用一个库来对图进行优化。由于这个库的代码完全超出了我的想象,我放弃了尝试将其适应自己的需求。它的一个函数用于计算平滑度惩罚,并且只接受四个参数。然而,我需要一个额外的参数(一个包含许多值的矩阵)来正确计算惩罚值。矩阵最初存储为Mat(opencv)对象,然后加载,所以我不能只将其声明为全局。有没有任何方法可以获取这个变量,并使所有可能需要它的方法都可以访问它?
好吧,所以我太草率了,正如预期的那样,"快速而肮脏"的解决方案结果很糟糕。正如Miki所说,我可以先声明全局变量,然后设置值。虽然这是有效的,但它看起来并不好。所以我花了一些时间,发现我需要的函数可以接收一个包含必要数据的结构,这样我就可以在没有糟糕设计的情况下做我需要的事情。
在不了解代码的情况下,我理解您想要一个全局变量,使方法可以访问。一种方法是声明一个Singleton,它保存指向实际Mat struct
的指针。
创建Mat struct
时,将其指针传递给Singleton。在删除Mat struct
时,您告诉Singleton重置。例如
class MatSingleton
{
public:
MatSingleton() : pMatInstance(nullptr) {}
~MatSingleton() {}
static MatSingleton& GetInstance()
{
static MatSingleton instance;
return instance;
}
bool IsMatAvailable()
{
return pMatInstance != nullptr;
}
void SetMat(Mat *pMat) { pMatInstance = pMat; }
Mat* GetMat() const { return pMatInstance; }
private:
Mat *pMatInstance;
};
[...]
// Load and fill LoadedMatStruct and inform the Singleton
MatSingleton::GetInstance().SetMat( &LoadedMatStruct );
// check if the Mat structure can be accessed
if (MatSingleton::GetInstance().IsMatAvailable())
{
// do smth. with Mat
Mat *pMatInstance = MatSingleton::GetInstance().GetMat();
}
// Somewhere else in the code where the Mat structe is destroyed, it is necessary to inform the Singleton
MatSingleton::GetInstance().SetMat( nullptr );
注意:这个演示代码不是线程安全的。它应该只是说明这个想法。
相关文章:
- 如何使用 llvm-10 库在C++定义 LLVM 全局值变量?
- 在.cpp文件之间传递全局字符串变量?
- 具有全局定义变量的递归比没有全局定义变量的递归函数获得更多的堆栈.为什么?(跳入C++)
- 为什么使用 SPI 时,全局缓冲区变量产生的结果与局部缓冲区变量不同
- 全局销毁期间全局布尔变量可靠吗?
- 全局自动变量可以在 h 文件中声明吗?
- 将全局外部变量的私有版本与 OpenMP 结合使用
- 使用全局 lua_State* 变量
- 为什么C 17中的全局内线变量和静态内线成员需要警卫
- 为全局constexpr变量生成唯一值
- C++:为全局类变量赋值
- 共享库中 __attribute__((构造函数)) 的全局/静态变量初始化问题
- 全局静态变量不"staying defined"函数外部
- 为什么不调用全局静态变量的析构函数
- 全局使用变量定义和C 声明
- 定义,初始化全局const变量是安全的吗?
- C 全局对象变量内存释放
- 全局静态变量阴影
- C++ 中的全局类变量与指针
- 可以静态访问全局静态变量的静态函数