如何保护具有非const方法的全局对象
How to protect a global object which has non-const methods
我需要在单线程应用程序中将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.
}
相关文章:
- 从 const 对象访问非 const 方法
- 为什么我可以调用一个从const方法更改成员的方法
- 使用新的c++返回值语法的Const方法
- const_cast const 方法中的"this"将"this"分配给外部变量?
- const 方法使用引用修改对象
- 从具有相同基数的另一个派生类调用派生类的非 const 方法
- 返回非常量引用编译的 Const 方法
- C++:无法从 const 方法返回对象的shared_ptr
- 是否可以从 const 方法迭代链表
- 为什么在const和非const方法中删除代码重复不是不确定的行为
- 在使用指向 const 和非 const 方法的成员指针时减少模板专用化的数量
- "可变"变量只能由 const 方法之一可变?
- Golang中的const方法
- C++ 逻辑恒常性和 const方法的按值返回
- c++将标志添加到const方法中
- C++防止const方法通过成员指针或引用更改数据
- 为什么 const 方法不覆盖 C++ 中的非 const 方法?
- 如何在const方法中迭代映射
- 为什么没有标准化的方法来避免const方法的代码重复
- 修改 const 方法中的 pointee 值