从getter方法返回const和非const值 [英] return const and non-const value from getter method

查看:75
本文介绍了从getter方法返回const和非const值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在此处问了一个问题,未能获得令人满意的答复,我仍在思考这个话题,因此开始这个新问题,希望我可以更好地描述我的想知道.

I asked one question here which did not get desirable response, I am still pondering on the topic, so start this new question, hopefully I can describe my wondering better.

我有这样的代码:

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()返回一个自由指针,该指针允许调用者自由更新数据.这让我很na,我认为解决方案编译器可以帮助执行语义检查.

You can see dump_p() is really a read-only function, but get_p() returns a free pointer which allows caller to update the data freely. This is nagging to me, I am thinking a solution compiler can help enforcing the semantic check.

这就是我的想法:

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 ++不允许仅使用具有不同返回类型的重载方法.

Add this get_rdonly_p() because c++ does not allow overloading method with different return type only.

我疯了吗?或您有什么解决方案?

Am I going nuts? Or what is your solution?

[更新]感谢Adrian,这可能是解决方案.但是我仍然会碰墙-您提到的非const版本get_p()不能100%满足我,该函数本身不会更改任何struct A,但是我没有将其声明为const,这是唠叨.

[UPDATE] Thanks Adrian, that might be the solution. But I am still banging my head against wall - the non-const version get_p() you mentioned does not 100% satisfies me, the function itself does not change any of the struct A, but I do not declare it as const, this is nagging.

让我坚持检查您的答案,很可能是这样,也许c ++在语言级别上缺少一些构造.

Let me hold checking yours as the answer, very likely it is, maybe c++ lacks some construct at language level.

推荐答案

您已经快懂了.

struct A
{
  P* get_p();
  const P* get_p() const;
};

这会根据 A 是否为const来重载 get_p .如果 A 是const,则直接访问指针的调用者应该不能更改它.非const版本不会直接修改 A ,但允许调用者通过返回的指针进行修改.

This overloads get_p depending on whether the A is const or not. If A is const, then a caller that gets direct access to the pointer should not be able to change it. The non-const version doesn't directly modify the A, but it allows the caller to do so via the returned pointer.

这是具有直接访问器的库中的常见模式.

This is a common pattern in libraries that have direct accessors.

这篇关于从getter方法返回const和非const值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆