使用变量作为全局变量

Using a variable as global

本文关键字:全局变量 变量      更新时间:2023-10-16

我正在使用一个库来对图进行优化。由于这个库的代码完全超出了我的想象,我放弃了尝试将其适应自己的需求。它的一个函数用于计算平滑度惩罚,并且只接受四个参数。然而,我需要一个额外的参数(一个包含许多值的矩阵)来正确计算惩罚值。矩阵最初存储为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 );

注意:这个演示代码不是线程安全的。它应该只是说明这个想法。