c++编译可以通过,运行的时候崩溃,运行到setCustom函数,this值为NULL,str输入值正常
class GooseStatInfo {
private:
std::string _custom;
public:
void setCustom(const std::string& str) {
_custom = str;
//debug 编译到此处str为字符串,this 值为NULL
}
std::string getToString() {
Serial gs;
gs.update(_custom);
// ... other codes
}
};
class ABRInt {
private:
GooseStatInfo* _stat;
ABRInt(ABRConfig& config, StatInfo* s) {
_stat = s;
// ... other codes
}
void onEvent(const std::shared_ptr<ABREvent>& event) {
std::string results = ABRCustC::getStatInfo();
//需要把results的结果发到_custom,ABRCustC::getStatInfo()返回的结果为str类型,做了c.str()处理
_stat->setCustom(results);
// ... other codes
}
};
编译输出
编译语法没有错误
class ABRInt {
private:
GooseStatInfo* _stat;
ABRInt(ABRConfig& config, StatInfo* s) {
_stat = s;
// ... other codes
}
void onEvent(const std::shared_ptr<ABREvent>& event) {
std::string results = ABRCustC::getStatInfo();
//需要把results的结果发到_custom,ABRCustC::getStatInfo()返回的结果为str类型,做了c.str()处理
//这里加上判断就可以了
if(_stat != NULL)
_stat->setCustom(results);
// ... other codes
}
};
应该是事件发生前还未运行初始化代码
该回答引用ChatGPT
这个编译错误可能是因为 _stat 指针未初始化或指向了 NULL。在 ABRInt 的构造函数中,_stat 被设置为 s,但是 s 可能是 NULL。在使用 _stat 之前,您应该确保它已经被正确地初始化。
您可以在 ABRInt 的构造函数中添加以下检查,确保 s 不是 NULL:
ABRInt(ABRConfig& config, StatInfo* s) {
if (s == NULL) {
// handle the error, e.g. throw an exception
throw std::runtime_error("s is NULL");
}
_stat = dynamic_cast<GooseStatInfo*>(s);
if (_stat == NULL) {
// handle the error, e.g. throw an exception
throw std::runtime_error("s is not of type GooseStatInfo");
}
// ... other codes
}
此外,在 GooseStatInfo::setCustom() 中,您可以添加断言语句来确保传递给函数的参数不是 NULL。例如:
void setCustom(const std::string& str) {
assert(&str != NULL);
_custom = str;
// ... other codes
}
这将在运行时检查指针是否为 NULL,并在指针为 NULL 时导致程序崩溃,以便及早发现和修复错误。
不知道你这个问题是否已经解决, 如果还没有解决的话: