An easy question on Pointer



  • I have a main class where I create an Object
    @QTSClient= new QTcpSocket();@
    After that I pass the pointer to a function
    @void Call(QTcpSocket *QTSClient= NULL);@
    in the Call function I delete and NULL the pointer like this:
    @delete QTSClient;
    QTSClient= NULL;@
    Really, the QTSClient is deletet but, in the main class, the QTSClient object results to be deleted but not = NULL.
    Can you explain to me why?



  • Why should it be NULL?

    A pointer is simply a memory address. So you are passing the memory address, which is stored in the QTSClient variable, into the sub-function. And you are passing it "by value", not "by reference". Inside the sub-function, you delete the object at that address. Now the value of QTSClient points to some invalid address, because the object no longer exists! This is called a "dangling" pointer. Inside the sub-function you also set the local variable QTSClient to NULL. But why should the variable QTSClient in the main function have become NULL too?

    It obviously doesn't. It still contains the old (now invalid) address!

    --

    What you could do is passing a pointer to the pointer:
    @void Call(QTcpSocket **QTSClient)
    {
    delete (*QTSClient);
    *QTSClient= NULL;
    }@

    And then call it like this:
    @main()
    {
    QTSClient = new QTcpSocket();
    Call(&QTSClient);
    }@

    --

    Yet another option is using Smart-Pointers instead of "raw" pointers...



  • @ void Call(QTcpSocket **QTSClient)
    {
    delete (*QTSClient);
    *QTSClient= NULL;
    }@

    Perfect!!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.