Amomum
Amomum

Reputation: 6503

Segmentation fault with QHostAddress

I'm trying to make a wrapper class for QUdpSocket; it should send datagrams only to a single endpoint. So, naturally, I pass destination address and port to the constructor and save it for late use:

class Wrapper
{

public:

    Wrapper(const QHostAddress & destinationAddress, quint16 destinationPort) :
        destAddress(destinationAddress),
        destPort(destinationPort)
    {}

    void sendData(char * data, uint32_t size)
    {
        udpSocket.writeDatagram(data, size, destAddress, destPort);
    }

    QUdpSocket udpSocket;

    const QHostAddress & destAddress;
    quint16 destPort;    

};

It compiles just fine, however, when I call sendData there is a segmentation fault. In the debugger all I can see is that destAddress is "optimized out reference". If I just put an actual address there everything works fine. So it looks like destAddress is some sort of a null reference.

But there is no such thing as null reference, is it? So what is going on? I'm clearly missing something.

Upvotes: 0

Views: 583

Answers (1)

Matt
Matt

Reputation: 15196

Simply change const QHostAddress &destAddress to QHostAddress destAddress inside class' declaration and it will be OK.

Reference is not a true variable. Besides "syntax sugar", it's just the pointer internally. And just like ordinary pointer, it needs the "host" variable to exist. You, probably, already destructed the ct's argument, so caught the error on dereferencing the stored ref.

Upvotes: 1

Related Questions