从getter方法返回常量和非常量值

return const and non-const value from getter method

本文关键字:常量 非常 返回 getter 方法      更新时间:2023-10-16

我在这里问了一个问题,但没有得到理想的回答,我仍在思考这个话题,所以开始这个新问题,希望我能更好地描述我的疑惑。

我有一个这样的代码:

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,但它允许调用方通过返回的指针进行修改。

这是具有直接访问者的库中的常见模式。