Dynamic mem allocation in local scope okay?
-
In the snippet below.. how come the dynamic allocation QState *state = new QState(parent); is okay inside the "for" loop? I would've thought that doing that was forbidden as the scope of that dynamically allocated variable ceases to exist after the "for" loop. This is taken from animation/appchooser/main.cpp example I found in QtCreator but I noticed that is the general practice of doing things in Qt apps. Please guide me as I've been experiencing some memory leakages and I wonder if this one could be the cause.
void createStates(const QObjectList &objects,
const QRect &selectedRect, QState *parent)
{
for (int i = 0; i < objects.size(); ++i) {
QState *state = new QState(parent);
state->assignProperty(objects.at(i), "geometry", selectedRect);
parent->addTransition(objects.at(i), SIGNAL(clicked()), state);
}
} -
In the snippet below.. how come the dynamic allocation QState *state = new QState(parent); is okay inside the "for" loop? I would've thought that doing that was forbidden as the scope of that dynamically allocated variable ceases to exist after the "for" loop. This is taken from animation/appchooser/main.cpp example I found in QtCreator but I noticed that is the general practice of doing things in Qt apps. Please guide me as I've been experiencing some memory leakages and I wonder if this one could be the cause.
void createStates(const QObjectList &objects,
const QRect &selectedRect, QState *parent)
{
for (int i = 0; i < objects.size(); ++i) {
QState *state = new QState(parent);
state->assignProperty(objects.at(i), "geometry", selectedRect);
parent->addTransition(objects.at(i), SIGNAL(clicked()), state);
}
}@Loquat said in Dynamic mem allocation in local scope okay?:
QState *state = new QState(parent);- The local variable
stategoes out of scope and is destroyed. - The
new QStatecreated object persists. - The "magic" of any class derived from
QObjectwhich is created vianew QState(parent)is that it gets attached to its parentQObjectand when that is destroyed its code destroys its children too. So you don't leak. Read Object Trees & Ownership.
- The local variable