我正在通过push_back()将元素添加到c ++ 11列表中。在添加元素之前,我正在通过cout打印出调试消息。现在,当我删除cout语句时,我使用push_back追加到列表的元素中的值已损坏。我可以使用googletest进行测试。
下面您将看到工作代码。当我注释掉cout语句时,sensor_scan_list的最后一个元素中的值似乎已损坏。在我看来,错误在于表的实例化或测试代码中。仅current_sensor.state的状态变量似乎已损坏(请参见下文)。
当我保留cout语句时,一切正常。这是一个很奇怪的问题,有人知道为什么会发生这种情况吗?
代码段:
void MessageHandler::processSensorHeader(TelemetryMessageInterface * p_Message)
{
cout << "DEBUG: sensor header element added\n";
addSensorHeader(p_Message);
send_message(encoder->confirm(((SensorHeaderMessage *)p_Message)->getMessageId())); //ACK
}
void MessageHandler::addSensorHeader(TelemetryMessageInterface * p_message)
{
Sensor new_sensor;
new_sensor.manufacturerId = ((SensorHeaderMessage *)p_message)->getManufacturerId();
new_sensor.deviceId = ((SensorHeaderMessage *)p_message)->getDeviceId();
new_sensor.state |= SENSOR_HEADER_DETECTED;
sensor_scan_list.push_back(new_sensor);
}
Googletest代码:
TEST(MessageHandlerTest, processSensorHeader)
{
TelemetryEncoder * encoder = new TelemetryEncoder();
TelemetryMessageInterface * p_Message;
MessageHandler message_handler;
Sensor current_sensor;
list <Sensor> :: iterator p_List;
p_Message = encoder->encodeSensorHeader(0x0101,0x0202,0x0303);
//add sensor
message_handler.processSensorHeader(p_Message);
p_List = message_handler.sensor_scan_list.begin();
current_sensor = *p_List;
EXPECT_EQ(current_sensor.deviceId, 0x0303);
EXPECT_EQ(current_sensor.manufacturerId, 0x0202);
EXPECT_EQ(current_sensor.state, 1);
p_Message = encoder->encodeSensorHeader(0x0203,0x0302,0x0403);
//add new sensor
message_handler.processSensorHeader(p_Message);
current_sensor = *++p_List;
EXPECT_EQ(current_sensor.deviceId, 0x0403);
EXPECT_EQ(current_sensor.manufacturerId, 0x0302);
EXPECT_EQ(current_sensor.state, 1);
p_Message = encoder->encodeSensorHeader(0x0102,0x0202,0x0303);
message_handler.processSensorHeader(p_Message);
current_sensor = *++p_List;
EXPECT_EQ(current_sensor.deviceId, 0x0303);
EXPECT_EQ(current_sensor.manufacturerId, 0x0202);
EXPECT_EQ(current_sensor.state, 1);
}
传感器类别:
class Sensor : public sensor_interface {
public:
Sensor();
virtual ~Sensor();
uint16_t manufacturerId;
uint16_t deviceId;
char name[SENSOR_INFORMATION_LENGTH];
uint8_t state;
};
Googletest输出的错误代码(注释已注释掉):
[ RUN ] MessageHandlerTest.processSensorHeader
../test/inc/test_messageHandler.cpp:77: Failure
Expected: current_sensor.state
Which is: '\xC1' (193)
To be equal to: 1
../test/inc/test_messageHandler.cpp:93: Failure
Expected: current_sensor.state
Which is: '\xF1' (241)
To be equal to: 1
[ FAILED ] MessageHandlerTest.processSensorHeader (0 ms)
答案 0 :(得分:1)
public Date? start_date { get; set; }
成员变量具有错误值的问题可能是由于state
类未在构造上初始化Sensor
所致。
因此,将state
应用于未初始化的变量将导致结果不一致或错误。
当然,解决方法是确保成员具有已知的构造初始值,在这种情况下,|=
在初始化state
时应为0。