gpt4 book ai didi

c++ - QStates 的内存管理添加到 QStateMachine

转载 作者:太空狗 更新时间:2023-10-29 23:44:17 24 4
gpt4 key购买 nike

以下代码由于内存损坏而导致崩溃。我假设这是因为 delete pTestStateMachine 试图删除未在堆中分配的内存。对吗?

如果是这样,是否意味着 QStateMachine::addState(QAbstractState * state) 必须始终传递动态分配的内存?遗憾Qt docs没有指定任何此类条件。我在这里缺少什么?

class CTestClass
{
public:
QState m_pTestState;
};

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

QStateMachine *pTestStateMachine;
CTestClass TestClass;

pTestStateMachine = new QStateMachine();
pTestStateMachine->addState(&(TestClass.m_pTestState));
pTestStateMachine->setInitialState(&(TestClass.m_pTestState));
pTestStateMachine->start();

pTestStateMachine->stop();
delete pTestStateMachine;

return a.exec();
}

最佳答案

does it imply that QStateMachine::addState(QAbstractState * state) must always be passed an dynamically allocated memory?

完全没有。 QState 没有任何特殊之处,同样的警告适用于任何 QObject。回想一下,QObject 是其他 QObject 的容器:它拥有它们,除非它们先被单独销毁,否则将尝试删除 子对象在 QObject::~QObject 中。

您的代码可以通过多种方式修复 - 在所有情况下,目标是不让 ~QObject 删除它不应该删除的子状态。

如果让编译器完成它应该做的工作,一切都会变得非常简单。您使用原始拥有指针而不是在定义点初始化它们的代码风格是非惯用的,并且经常会激发您遇到的错误。如果您有一个拥有指针,请使用 std::unique_ptrQScopedPointerdelete 和手动内存管理仅属于单一用途的资源管理类。它根本不属于通用代码:将每个显式 delete 都视为错误。你不需要它们。

class CTestClass
{
public:
QState m_pTestState;
};

// Fix 1: Don't mix automatic storage duration with dynamic storage duration
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
{
QStateMachine TestStateMachine;
CTestClass TestClass;
TestStateMachine.addState(&TestClass.m_pTestState);
TestStateMachine.setInitialState(&TestClass.m_pTestState);
TestStateMachine.start();
TestStateMachine.stop();
} // <-- here the compiler emits
// TestClass.~TestClass()
// ...
// TestStateMachine.~QStateMachine()
// ...
// TestStateMachine.~QObject()
}

// Fix 2: Make sure that the child doesn't outlive the parent.
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
{
QScopedPointer<QStateMachine> TestStateMachine(new QStateMachine);
CTestClass TestClass;
TestStateMachine->addState(&TestClass.m_pTestState);
TestStateMachine->setInitialState(&TestClass.m_pTestState);
TestStateMachine->start();
TestStateMachine->stop();
} // <-- here the compiler emits
// TestClass.~TestClass()
// ...
// TestStateMachine.~QScopedPointer()
// delete data;
// data->~QStateMachine
// ...
// data->~QObject
// free(data)
}

关于c++ - QStates 的内存管理添加到 QStateMachine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33108963/

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