我在类构造函数中有以下代码:
MqttSensorInterface::MqttSensorInterface(Client& client, String sensorTopic)
{
this->mqttClient = PubSubClient(client);
this->sensorTopic = sensorTopic;
this->askMeasureTopic = sensorTopic + "/askmeasure";
this->publishMeasureTopic = sensorTopic + "/measure";
}
但是在MqttSensorInterface
创建新对象后使用构造函数之后,构造函数中PubSubClient
实例化的对象就被破坏了(PubSubClient
调用了析构函数)。我是C ++的新手,不知道这段代码是否有问题。由于PubSubClient
对象是在构造函数中实例化的,但类成员mqttClient
设置为该对象,因此它的作用域是什么?
PubSubClient构造函数代码:
PubSubClient::PubSubClient(Client& client) {
this->_state = MQTT_DISCONNECTED;
setClient(client);
this->stream = NULL;
this->bufferSize = 0;
setBufferSize(MQTT_MAX_PACKET_SIZE);
setKeepAlive(MQTT_KEEPALIVE);
setSocketTimeout(MQTT_SOCKET_TIMEOUT);
}
编辑
通过以下方式使用成员初始化器列表解决:
MqttSensorInterface::MqttSensorInterface( Client& client, String sensorTopic): mqttClient(client)
当构造函数的主体
MqttSensorInterface::MqttSensorInterface(String sensorTopic)
{
WiFiClient wiFiClient;
this->mqttClient = PubSubClient(wifiClient);
this->sensorTopic = sensorTopic;
this->askMeasureTopic = sensorTopic + "/askmeasure";
this->publishMeasureTopic = sensorTopic + "/measure";
}
获取控件,该控件已使用默认构造函数创建了数据成员mqttClient,PubSubClient
前提是在类定义中没有该数据成员的显式初始化程序,
所以在这句话里面
this->mqttClient = PubSubClient(wifiClient);
将PubSubClient
通过构造函数的显式调用创建该类型的临时对象,PubSubClient(wifiClient)
并this->mqttClient
使用复制分配操作符或移动分配操作符将该临时对象分配给数据成员。在语句执行结束时,临时对象被销毁。
如果可能,可以在构造数据成员的过程中在构造函数的mem-initializer列表中初始化数据成员。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句