等待状态改变的方法应该是 const 吗?

发布于 2024-08-26 21:09:08 字数 286 浏览 7 评论 0原文

在多线程场景中,我有一个这样的方法:

bool WaitForChange( time_duration WaitTime ) const;

该方法要么等待,直到对象的状态发生变化并返回 true,要么直到超时超时(怎么说?)并返回 false。

我的直觉是,const 是为了防止方法本身产生不必要的副作用,所以这很好。但话又说回来,有些用户可能认为该方法的状态无法更改,因为该方法被声明为 const。该用户是否愚蠢,或者我应该将该方法设置为非 const 以避免混淆?

In a multithreaded scenario, I have a method like this:

bool WaitForChange( time_duration WaitTime ) const;

This method waits either until the state of the object has changed and returns true, or until the timeout times out (how do you say that?) and returns false.

My intuition is, that const is to protect against unwanted side-effects of the method itself, so this is fine. But then again, some user might think that the state of the could not have changed, since the method is declared const. Is that user stupid, or should I make the method non-const in order to avoid confusion?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

沩ん囻菔务 2024-09-02 21:09:08

通过将该方法声明为 const,您可以说“调用此方法不会更改对象的状态”。这是(希望)是真的。所以让它成为常量。

如果有人认为常量性意味着“当调用此方法时,没有其他人可以更改对象状态”,那么这个人就错了。

By declaring the method as const, you say "Calling this method doesn't change the state of the object." This is (hopefully) true. So make it const.

If anybody thinks, const-ness means "While this method is called, no one else can change the object state" than that person is wrong.

薯片软お妹 2024-09-02 21:09:08

我投票支持持续性。

该方法本身不会改变任何东西,只是等待......

I vote for constness.

The method itself does not change anything, just waits...

∝单色的世界 2024-09-02 21:09:08

如果您正在等待查看对象成员是否已更改...那么易失性呢?

bool WaitForChange( time_duration WaitTime ) volatile

const 意味着对象的状态在整个函数调用过程中是相同的,所以我不会使用它。另一方面,易失性向编译器指示每当访问成员时都应该重新获取成员,如果您正在寻找更改,这可能就是您想要的。

If you're waiting to see if the object members have changed... what about volatile?

bool WaitForChange( time_duration WaitTime ) volatile

const implies the state of the object is the same throughout the function call, so I wouldn't use it. volatile, on the other hand, indicates to the compiler that the members should be re-fetched whenever they are accessed, which is probably what you want if you're looking for changes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文