如果成员函数调用破坏“constness”的函数,它仍然是 const 吗?
我想知道如果一个类的成员函数调用其他修改其数据成员的函数,它是否应该是 const 。一个很好的例子是公共成员函数,它使用私有成员函数来完成主要的工作。
void Foo::Show() const { // Doesn't directly modify data members in this function
ShowPig(); // One or all of these functions modify data members
ShowCow();
ShowBar();
}
也许不是最好的例子,但你明白了。
I'm wondering if a class's member function should be const if it calls other functions that modify its data members. A good example would be a public member function that uses private member functions to do the brunt of the work.
void Foo::Show() const { // Doesn't directly modify data members in this function
ShowPig(); // One or all of these functions modify data members
ShowCow();
ShowBar();
}
Maybe not the best example, but you get the idea.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
任何好的编译器都不允许这样做。您应该得到编译器错误。
Any Good compiler does not allow this. You should get the compiler error.
编译器不应该允许你这样做。下面的例子。
The compiler should not allow you to do that. Example below.
如果一个函数调用了修改某些数据的函数,那么应该说该函数本身修改了数据。它只是碰巧被抽象了。
所以不,该函数不应该是 const。
If a function calls functions that modify certain data, then it should be said that the function itself modifies data. It just happens to be abstracted.
So no, that function should not be const.
C++ 为您确实想要允许这种情况的罕见情况提供了 mutable 关键字。有时会发生这种情况,例如,如果您的函数不更改对象的逻辑状态,但可能会修改对象的一个或多个成员。
这些案例非常罕见。在绝大多数情况下,如果成员函数及其调用的任何函数都没有修改对象的状态,则应将成员函数标记为 const。
C++ provides the mutable keyword for the rare case that you actually want to allow this. And there are times where it happens, for instance if your function does not change the logical state of the object, but may modify one or more members of the object.
These cases are very rare. In the vast majority of cases you should mark the member function const if neither that function nor any function it calls modifies the state of the object.
是的,正如所指出的,编译器不会让你这样做。当然你无论如何都可以这样做,但是如果函数需要是 const 通常这是一个坏主意。如果它不需要是 const,就不要无缘无故地将它放在那里。 const 确实没有多大好处,而且有许多潜在的严重问题,有时你只是被迫使用它。
Yes, the compiler won't let you, as pointed out. Of course you can do it anyway but if the function needs to be const usually it's a bad idea. If it doesn't need to be const, don't just put it in there for no reason. There's really not much benefit to const and many potential serious problems, you just get forced into it at times.