如何保护具有非const方法的全局对象

How to protect a global object which has non-const methods

本文关键字:const 方法 对象 全局 何保护 保护      更新时间:2023-10-16

我需要在单线程应用程序中将Params类的一个实例作为全局对象公开。

作为安全措施,我希望防止客户端代码无意中覆盖对象本身。但是,我不能使用const限定符(如下例所示),因为有些类方法是非const的。

这个类可能会在代码的其他部分被重新实例化,所以我想避免改变它的内部来适应这种特殊的需要,例如,通过使用单例设计模式或对某些数据成员应用可变限定符。

我能想到的唯一解决方案是一个简单的包装器类,它的单个数据成员是一个可变的Params对象,但对于这样一个简单的需求,这似乎是一个可怕的解决方案。

我不了解c++的最新进展,所以也许有人能想出一个更优雅的解决方案。

// params.h
class Params
{
  ..
};
extern const Params params;
// params.cpp
#include "params.h"
const Params params;  // no good because class has mutable methods

如果你想要一个不能被覆盖的可变对象,你可以将类的operator=设置为private/protected

我建议将全局Param对象与非成员函数包装在适当的命名空间中,然后使用私有的Param对象实现这些函数。

类似以下语句的内容:

GlobalParam.h:

#pragma once
namespace GlobalParam
{
   void setParam1(Args ...);
   void setParam2(Args ...);
   Type1 getParam1();
   Type2 getParam2();
   // etc.
}

GlobalParam.cc:

#include "GlobalParam.h"
namespace GlobalParam
{
   // Provide a function that returns a reference
   // to the global Param object. All functions make use of
   // this object. This function is not exposed to the users of
   // the API.
   Param& getParam()
   {
      static Param param;
      return param;
   }
   void setParam1(Args ... args) { getParam().setParam1(args...); }
   void setParam2(Args ... args) { getParam().setParam2(args...); }
   Type1 getParam1() { return getParam().getParam1(); }
   Type2 getParam2() { return getParam().getParam2(); }
   // etc.
}