0

I have class Connection:

class Connection{
    public: Connection(string usr, string pwd);
            ~Connection();
    private:
        Engine *        pEngine;
        AdmCallbacks * pAdmCallbacks;
        Callbacks *      pCallbacks;
        char *           fake[11];
        int              iFlags;
        int              iCode;
};

~Connection()
{
        delete pEngine;
        delete pCallbacks;
        delete pAdmCallbacks;
}

in main.cpp i do this code:

#include <iostream>
#include "Connection.h"
using namespace std;
int main()
{
  Connection *connection = new Connection("test","test");
  if (logedin)
      //do something
  else delete connection;
  if (connection != NULL)
    cout << "WTF" << endl;
  return 0;  
}

Output:

WTF

Why? I dont understand why the memory is not dispose.. Help me please, Thx!

mrglut
  • 27
  • 5
  • 1
    Why do you think `delete`ing it will then set the pointer to `NULL`? (Hint: it won't - you are just responsible for not reusing it) – BoBTFish Mar 30 '15 at 10:16
  • @BoBTFish then how i can checked that the pointer is null after deleting? I need to set it to NULL? – mrglut Mar 30 '15 at 10:21
  • 1
    Why do you need it to be `NULL`? It's `delete`d. There should be no need for you to go near it again. But yes, in some cases you might want to reuse a pointer, in which case you would manually set it to `NULL` to know that you need to allocate something there again before using it. – BoBTFish Mar 30 '15 at 10:23
  • @BoBTFish Yes, i need to use it again, looak at the code, i add some lines. So if loginfailes (in else) i need to add "connection = NULL" after deleting ? – mrglut Mar 30 '15 at 10:35
  • 1
    To be clear, you don't need to set the pointer to NULL before reusing it. Furthermore, consider not using new at all. `Connection *connection = new Connection("test","test");` could be `Connection connection ("test","test");` – Neil Kirk Mar 30 '15 at 10:45
  • @NeilKirk its really good, but i have another question: What will happen with class connection, if i set it to NULL without deleting? the memory is disposed? – mrglut Mar 30 '15 at 10:52
  • You will leak memory. In modern C++ you should avoid new as much as possible and use smart pointers if necessary. This makes it harder to leak memory. – Neil Kirk Mar 30 '15 at 11:01
  • @NeilKirk hm, i just test it, and i dont have any leaks – mrglut Mar 30 '15 at 11:03
  • How do you know that? – Neil Kirk Mar 30 '15 at 11:06
  • @NeilKirk D: okay, i understand you. Thanks! – mrglut Mar 30 '15 at 11:08

0 Answers0