0

What happens to the myClass pointer when the foo function finishes? Is it automatically deleted?

What happens to myThread pointer when the bar function finishes? (Supposing that myThread points to a QThread object)

void foo()
{
    MyClass *myClass = new MyClass();
    myClass->doSomething();
}

void bar()
{
    // Suppose that MyThread is a QThread class
    MyThread* myThread = new MyThread(2.5);

    // Connect the Thread to get the result
    connect(myThread, SIGNAL(sendResult(double)), this, SLOT(getResult(double)));

    // Start the thread
    myThread->start();
}

Thanks in advance

KelvinS
  • 2,870
  • 8
  • 34
  • 67
  • 2
    When you instantiate an object with `new` it will survive until `delete` is called on it. Since you are using raw pointers, they will survive until you call `delete` yourself or pass them to consuming functions that contain a call to `delete`. – François Andrieux Feb 08 '17 at 20:00

1 Answers1

3

You're in C++ here, no one's going to delete your objects if you don't do so. Every new you write requires you to write a delete to free the memory (like in C every malloc needs a free).

Only objects gets deleted:

void foo()
{
    MyClass myClass;
    myClass.doSomething();
}

Then MyClass's destructor is invoked when foo returns. In general, unless you need the object to be persistent out of your scope, prefer objects over pointers, it will prevent memory leaks in your code.

Special cases to consider:

Note: For QThread, you should ask it to be deleted when done. See When or how to delete QThread in Qt.

Community
  • 1
  • 1
jpo38
  • 20,821
  • 10
  • 70
  • 151
  • You should tell OP to prefer unique_pointer over shared_pointer when possible (ie, almost always). Also, avoid using pointers altogether when not necessary. – dureuill Feb 08 '17 at 20:06
  • Thanks for the answer. In the bar function, I am creating a pointer to a thread object. Should I delete this pointer only when the thread finishes, right? Then I need to declare the pointer in the global scope to it be accessible by other functions (e.g. getResult(double))? – KelvinS Feb 08 '17 at 20:08
  • 1
    @KelvinSalton: It's typical for GUI frameworks to perform custom memory handling. In such cases, you should always follow the framework's best practices and documentation and not try to interfere by using smart pointers. At the same time, you must not assume that GUI frameworks are representative of C++ memory management in general. – Christian Hackl Feb 08 '17 at 20:17