0

I have a QMap that includes QSharedPointers as values. Everytime I try to loop through the map and qDebug the results I'm getting memory handling erros.

Values of the map are objects of Team class which inherits from QObject.

QMap definition:

QMap<QString, QSharedPointer<Team>> teams;

Implementation:

auto json_result = GetJsonObject(raw_json);
auto json_error = json_result.second;
if (json_error.error != QJsonParseError::NoError)
{
    ShowJsonParseError(json_error);
}
auto json_obj = json_result.first;
for (QString& city : json_obj.keys())
{
    auto team_obj = json_obj[city].toObject();
    teams.insert(city, QSharedPointer<Team>(new Team(this, city,
                                   team_obj["Arena"].toString())));
}
for (auto team : teams.values())
{
    qDebug() << team->getCity() << " - " << team->getArena();
}

The teams map content:

  • ("Detroit", Team), // Team object with parameter "Detroit" as city and "Joe Louis Arena" as arena.
  • ("Pittsburgh", Team) // Team object with parameter "Pittsburgh" as city and "Mellon arena" as are.

qDebug output is:

"Detroit" - "Mellon Arena"
"" - "Mellon Arena"

What happens here? Why does output take city from correct object and area from next object?

I come from python background and obviously memory is handled incorrectly here. But I have searched for examples and don't know what is wrong here.

I tried to get keys from map also and searching value from map using that but then program crashes after first loop.

demonplus
  • 5,613
  • 12
  • 49
  • 68
mmok
  • 1
  • 1
  • 1
    The example is not complete. It should work if the code is put into one function block. The memory corruption can happen if `Team` object is destroyed before reading its pointer from `QMap`. It can happen, since `QObject` may be destroyed by its parent. There is suspicious argument `this` in the `Team` constructor that looks like a pointer to parent `QObject` – Orest Hera Oct 31 '15 at 17:43
  • You are right I was taking reference to json_object data and that was destroyed. Thanks. – mmok Nov 01 '15 at 10:25

0 Answers0