gpt4 book ai didi

c++ - 关于C++指针的疑惑

转载 作者:行者123 更新时间:2023-11-27 23:56:47 26 4
gpt4 key购买 nike

foo 函数完成后,myClass 指针会发生什么变化?是否自动删除?

bar 函数完成后,myThread 指针会发生什么变化? (假设myThread指向一个QThread对象)

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();
}

提前致谢

最佳答案

你在这里使用 C++,如果你不这样做,没有人会删除你的对象。您编写的每个 new 都需要您编写一个 delete 来释放内存(就像在 C 中每个 malloc 都需要一个 free).

只有对象被删除:

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

然后 MyClass 的析构函数在 foo 返回时被调用。一般来说,除非您需要对象在您的范围之外持久化,否则优先选择对象而不是指针,这将防止代码中的内存泄漏。

要考虑的特殊情况:

注意:对于QThread,完成后应该要求删除。参见 When or how to delete QThread in Qt .

关于c++ - 关于C++指针的疑惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42122496/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com