KelvinS
KelvinS

Reputation: 3061

Doubts about C++ pointers

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

Upvotes: 0

Views: 111

Answers (1)

jpo38
jpo38

Reputation: 21514

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.

Upvotes: 3

Related Questions