Tom
Tom

Reputation: 4087

Qt deletion pointer method

In a Qt project I have a method

void ProtocolHandler::interpretData(uint8_t packet_id){
    PacketClass *packet = new RSP2StatusPacket(_packet_buf);
    emit packetReceived(packet);
}

where I declare an object packet of type PacketClass and then I emit the signal

packetReceived (PacketClass*)

In another class I have the following slot:

void ReceiverCommands::processReceivedPacket(PacketClass* pkt)
{
    status_packet *payload = pkt->getPayload();

    delete pkt
}

Is it correct to delete the newer PacketClass *packet in the slot method? Sometimes my program crashes so what is the best method to delete a pointer passed in a signal/slot (I suppose I must delete the pkt because I instantiate a new packet in "interpretData" method).

Upvotes: 2

Views: 323

Answers (2)

There can be an arbitrary number of slots attached to a signal (including zero and more than one!), so you should never expect a slot to deallocate memory passed via a naked pointer.

You should be passing a QSharedPointer<PacketClass> and use it. It will do the deletion as and when needed.

typedef QSharedPointer<PacketClass> PacketClassPtr;
Q_DECLARE_METATYPE(PacketClassPtr)

ProtocolHandler {
    ...
    Q_SIGNAL void packetReceived(PacketClassPtr packet);
}

void ProtocolHandler::interpretData(uint8_t packet_id){
    PacketClassPtr packet(new RSP2StatusPacket(_packet_buf));
    emit packetReceived(packet);
}

void ReceiverCommands::processReceivedPacket(PacketClassPtr pkt)
{
    status_packet *payload = pkt->getPayload();
}

Upvotes: 2

TheDarkKnight
TheDarkKnight

Reputation: 27611

Assuming PacketClass is derived from QObject, then call the deleteLater function: -

pkt->deleteLater();

This will handle deleting the object at the right time, after it has been through handling signals and slots and when control is returned to the event loop.

See the documentation for deleteLater here, which is also relevant for Qt4

Upvotes: 1

Related Questions