等待状态改变的方法应该是 const 吗?
在多线程场景中,我有一个这样的方法:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通过将该方法声明为 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.
我投票支持持续性。
该方法本身不会改变任何东西,只是等待......
I vote for constness.
The method itself does not change anything, just waits...
如果您正在等待查看对象成员是否已更改...那么易失性呢?
const 意味着对象的状态在整个函数调用过程中是相同的,所以我不会使用它。另一方面,易失性向编译器指示每当访问成员时都应该重新获取成员,如果您正在寻找更改,这可能就是您想要的。
If you're waiting to see if the object members have changed... what about 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.