从getter方法返回常量和非常量值
return const and non-const value from getter method
我在这里问了一个问题,但没有得到理想的回答,我仍在思考这个话题,所以开始这个新问题,希望我能更好地描述我的疑惑。
我有一个这样的代码:
struct A
{
P* get_p() const;
};
void dump_p(const A *a)
{
const P* p = a->get_p();
...... dump out p's content for debugging purpose ......
}
void re-format(A *a)
{
P* p = a->get_p();
...... update p's content ......
}
您可以看到dump_p()实际上是一个只读函数,但get_p(。这一直困扰着我,我认为解决方案编译器可以帮助执行语义检查。
这就是我想到的:
struct A
{
P* get_p() const;
const P* get_rdonly_p() const;
};
void dump_p(const A *a)
{
const P* p = a->get_rdonly_p();
}
void re-format(A *a)
{
P* p = a->get_p();
}
添加此get_rdonly_p(),因为c++不允许只重载具有不同返回类型的方法。
我疯了吗?或者你的解决方案是什么?
[更新]谢谢Adrian,这可能是解决方案。但我仍然在碰壁——你提到的非const版本get_p()并不能100%满足我,函数本身没有改变任何结构A,但我没有将其声明为const,这很烦人。
让我继续检查你的答案,很可能是,也许c++在语言层面缺乏一些结构。
你几乎做到了。
struct A
{
P* get_p();
const P* get_p() const;
};
这将根据A
是否为常量来重载get_p
。如果A
是const,那么直接访问指针的调用方应该无法更改它。非const版本不直接修改A
,但它允许调用方通过返回的指针进行修改。
这是具有直接访问者的库中的常见模式。
相关文章:
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 什么时候在C++中返回常量引用是个好主意
- 代理对象的常量正确性
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 通过多个头文件使用常量变量
- 在cuda线程之间共享大量常量数据
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 是默认情况下分配给char数组常量的值
- 私有类型的静态常量成员
- OpenGL大的3D纹理(>2GB)非常慢
- 类似枚举的计算常量
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 使用常量键但非常量值进行映射
- 为什么`is_open()`非常常量
- 从getter方法返回常量和非常量值
- 阻止const类函数在引用成员上调用非常常量类函数
- C++初始化非常大的常量数组,最佳实践
- 提高c++中非常大的常量的可读性