我在类构造函数中有这样的代码:
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";
}
获取已使用默认构造函数PubSubClient
创建的数据成员mqttClient的控件,前提是类定义中没有数据成员的显式初始值设定项,
所以在这个陈述中的身体里面
this->mqttClient = PubSubClient(wifiClient);
通过显式调用构造函数PubSubClient(wifiClient)
来创建类型为PubSubClient
的临时对象,并且使用复制赋值运算符或移动赋值运算符将此临时对象分配给数据成员this->MQTTClient
。 在语句执行结束时,临时对象被销毁。
如果可能的话,可以在构造数据成员期间在构造函数的mem-initializer列表中初始化数据成员。