Search code examples
qtscopestlshared-ptr

Segmentation fault when adding shared_ptr to list


Let me explain. In this method I'm trying to push new item to list.

spContainer ObjectsManager::createContainer(QStringList data, QVector2D onMapPosition) {
    spContainer new_container (new Container());
    new_container->setData(data);
    new_container->setPosistion(onMapPosition);
    containers.push_back(new_container);

    emit containerAdd(new_container->toQVariantMap());

    return new_container;
}

spContainer is a typedef:

typedef std::shared_ptr<Container> spContainer;

containers is a std::list

class ObjectsManager : public QObject {
...
public:
    spContainer createContainer(QStringList data, QVector2D onMapPosition);
...

private: 
    std::list<spContainer> containers;
};

The same error while using QList or QVector. It's very strange, because if I will add to method new QList and try to push pointer into container...

spContainer ObjectsManager::createContainer(QStringList data, QVector2D onMapPosition) {
    spContainer new_container (new Container());
    new_container->setData(data);
    new_container->setPosistion(onMapPosition);
    QList<spContainer> conts;
    conts.push_back(new_container);
    //containers.push_back(new_container);

    emit containerAdd(new_container->toQVariantMap());

    return new_container;
}

It will work fine!

WAT? What the difference?! Can someone explain me what's going on?


Solution

  • My bad! The problem was that I call the method of uninitialized object!

    the fix is:

    _objManager = spObjectsManager (new ObjectsManager);
    _objManager->createContainer(data);