[英]Is it safe to call a virtual method in the constructor when using a scope resolution operator?
I have a class hierarchy where every class has a method compute
that will trigger some (re-) computation.我有一个 class 层次结构,其中每个 class 都有一个方法compute
,它将触发一些(重新)计算。 This method is a virtual method (and it's pure virtual in the base class).这个方法是一个虚拟方法(它在基类中是纯虚拟的)。 In some cases I would like to call this method from the constructor to immediately set up my instance.在某些情况下,我想从构造函数中调用此方法来立即设置我的实例。
Of course this can be dangerous.当然,这可能很危险。 Eclipse CDT Code Analysis issues the error "Calling a virtual method in constructor can cause crashes and unexpected behavior". Eclipse CDT 代码分析发出错误“在构造函数中调用虚拟方法可能导致崩溃和意外行为”。 I understand the error message and its reason.我了解错误信息及其原因。 Please, please do not tell me why this should be avoided!!!请,请不要告诉我为什么要避免这种情况!!!
To make the error message and (more important) the potential of having an error go away, I have introduced a scope resolution operator.为了使错误消息和(更重要的)出现错误 go 的可能性消失,我介绍了 scope 分辨率运算符。 So the constructor now looks like that:所以构造函数现在看起来像这样:
MyClass::MyClass()
{
MyClass::compute();
}
I would expect that to be absolutely safe.我希望那是绝对安全的。 But Eclipse code analysis continues to display the error message.但是Eclipse代码分析继续显示错误信息。 Why?为什么? It is not possible to call an unexpected method.不可能调用意外的方法。 And if the method was pure virtual in MyClass
, the compiler would tell me so.如果该方法在MyClass
中是纯虚拟的,编译器会这样告诉我。
Is this an Eclipse code analysis bug or am I missing something?这是 Eclipse 代码分析错误还是我遗漏了什么?
Edit: the scope resolution operator is supposed to suppress virtual resolution.编辑: scope 分辨率运算符应该抑制虚拟分辨率。 Therefore I expect it to prevent all possible errors mentioned by the warning.因此,我希望它可以防止警告中提到的所有可能的错误。 Is my assumption true?我的假设是真的吗?
I would like to summarize the most important points from the comments/chat:我想总结评论/聊天中最重要的几点:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.