D 类不变式调用 const 函数
为什么以下代码会引发编译器错误:
class A
{
public:
int f() const
{
return 5;
}
protected:
invariant()
{
assert (f() == 5);
}
}
main.d(14): Error: Cannot call public/export function f from invariant
。
我理解不变性的概念;您想要在每次公共调用方法之间检查类的状态。
但是,不可变或常量成员函数无法更改类的状态(除非传递了 this ?),因此围绕这些函数的不变检查是多余的。可以将不变调用放在一边,并且不会出现无限循环,从而导致编译器错误。
我之所以想到这一点是因为我用对象创建了层次结构,它定义了:
bool hasParent() const
{
return (parent !is null);
}
在类内使用这个小函数更容易,但在外部也可能如此。但将其定义为 public 违背了 invariant()。
Why does the following throw a compiler error:
class A
{
public:
int f() const
{
return 5;
}
protected:
invariant()
{
assert (f() == 5);
}
}
main.d(14): Error: cannot call public/export function f from invariant
.
I understand the concept of invariant; you want to check the state of the class between every public call to a method.
However, immutable or const member functions cannot alter the state of the class (unless this
was passed?), so invariant checks surrounding those functions are redundant. The invariant call could be left aside and no infinite loop would appear, casting the compiler error wrong.
I came to this since I create hierarchies with objects, which define:
bool hasParent() const
{
return (parent !is null);
}
using this little function is easier within the class, but possibly outside too. But defining it public defies invariant().
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这很可能是一个遗漏。请随时在 Bugzilla 上提交增强请求。
It's most likely an omission. Feel free to file an enhancement request on Bugzilla.