使用qDebug流式输出指针指向值时为何会修改原指针值?
qDebug流式输出导致FlatBuffer结构体成员数值异常的问题
在使用qDebug流式输出打印FlatBuffer生成的ParametersT结构体成员后,原本赋值正常的float类型成员(erosion、planarity、tolerance_minor、tolerance_major)会变为接近0的异常值。移除该流式输出语句,或使用格式化字符串的qDebug调用时,数值则完全正常。
相关代码片段
赋值及流式输出代码:
def_pipelines_laser->pipelines[0]->param_laser[0]->erosion = erosion; def_pipelines_laser->pipelines[0]->param_laser[0]->planarity = CS_nominal/1000; def_pipelines_laser->pipelines[0]->param_laser[0]->tolerance_minor = (CS_nominal/1000) - toll_cs; def_pipelines_laser->pipelines[0]->param_laser[0]->tolerance_major = (CS_nominal/1000) + toll_cs; qDebug() << "Laser Data " << def_pipelines_laser->pipelines[0]->param_laser[0]->erosion << " " << def_pipelines_laser->pipelines[0]->param_laser[0]->planarity << " " << def_pipelines_laser->pipelines[0]->param_laser[0]->tolerance_minor << " " << def_pipelines_laser->pipelines[0]->param_laser[0]->tolerance_major;
ParametersT结构体定义:
struct ParametersT : public flatbuffers::NativeTable { typedef Parameters TableType; std::vector<std::unique_ptr<SmartDevice::Station::PipelineT>> pipelines{}; };
正常工作的格式化输出代码:
qDebug("Erosion = %s", std::to_string(def_pipelines_laser->pipelines[0]->param_laser[0]->erosion).c_str()); qDebug("Planarity = %s", std::to_string(def_pipelines_laser->pipelines[0]->param_laser[0]->planarity).c_str()); qDebug("Tolerance Min = %s", std::to_string(def_pipelines_laser->pipelines[0]->param_laser[0]->tolerance_minor).c_str()); qDebug("Tolerance Maj = %s", std::to_string(def_pipelines_laser->pipelines[0]->param_laser[0]->tolerance_major).c_str());
数值变化情况
调试前,上述成员变量为符合业务逻辑的正常数值;执行流式输出语句后,所有成员变为接近0的极小值。
可能的原因分析
- FlatBuffer NativeTable的const访问冲突:qDebug的流式运算符
<<可能对传入对象进行了非const的隐式转换或意外修改。FlatBuffer的NativeTable内部可能依赖未完全初始化的字段,或流式输出的重载函数错误修改了对象内存。 - 类型匹配问题:需确认
param_laser中的成员是否确实为float类型。若实际为其他类型(如double或自定义类型),qDebug流式输出可能因类型不匹配导致内存越界或误写。 - 智能指针生命周期问题:尽管使用了
std::unique_ptr,若param_laser内部对象的生命周期管理存在漏洞,流式输出时的内存访问可能触发未定义行为,间接篡改成员值。 - Qt流式输出重载陷阱:若
param_laser所属结构体未正确实现operator<<的const版本,qDebug可能调用非const重载,意外修改成员变量。
内容的提问来源于stack exchange,提问作者Matteo Barbieri
相关产品推荐
相关产品推荐

