我正在编写解析器,在转换时我无法区分普通类类型和数组类类型。
有类似下面的东西会对我有很大帮助:
if (expression causes segmentation fault)
do sth
else
do sth else
如果不是这样,那么区分两个类的好方法是什么?
if (base->type->GetType() != "") {
char *key = strcpy(key, base->type->GetType().c_str());
Node *node = (stack->front).Lookup(key);
if (node != NULL) {
theclass = dynamic_cast<ClassDeclaration *>(node);
}
if (!base->GetType()->IsEquivalentTo(GetType()))
errReport.FieldNotFoundInBase(field, type);*/
if (theclass->id->name){ // segfault happens here.
- 变量 theclass 有时被初始化为一个实际的类,有时被初始化为一个数组。当存在数组类而不是实际类时,段错误发生在
if (theclass->id->name) {
行中,因为数组类实际上没有名称字段。我真的没有办法告诉正在初始化类变量的类型。
最佳答案
如果node
是 ClassDeclaration
的实例, 然后 dynamic_cast<ClassDeclaration *>(node)
将返回 node
“转换”为 ClassDeclaration*
[1].否则,它返回 0(或者,更准确地说,nullptr
转换为 ClassDeclaration*
。
您不检查 nullptr
值(value)。取消引用 nullptr
几乎肯定会出现段错误(尽管从技术上讲它是 UB,所以它可以做任何事情。)
现在,可能发生了一些更深奥的事情并且段错误没有发生,因为 dynamic_cast
失败并返回 nullptr
然后您继续取消引用该值。这是可能的。如果您检查了返回值,我们都会确定。
注意 1:dynamic_cast
是可能的更改指针值,例如,如果转换为类型不是多重继承对象的第一个基类型。所以我可能不应该在“转换”这个词周围加引号。
关于c++ - 段错误 C++ 转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19474050/