将 shared_ptr 添加到列表时出现分段错误
Segmentation fault when adding shared_ptr 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
是一个类型定义:
typedef std::shared_ptr<Container> spContainer;
containers
是一个 std::list
class ObjectsManager : public QObject {
...
public:
spContainer createContainer(QStringList data, QVector2D onMapPosition);
...
private:
std::list<spContainer> containers;
};
使用 QList
或 QVector
时出现同样的错误。
这很奇怪,因为如果我将添加到方法 new QList 并尝试将指针推入容器...
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;
}
它会很好用!
瓦特?有什么区别?!有人可以向我解释发生了什么事吗?
我的错!
问题是我调用了未初始化对象的方法!
修复方法是:
_objManager = spObjectsManager (new ObjectsManager);
_objManager->createContainer(data);
让我解释一下。在这种方法中,我试图将新项目推送到列表中。
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
是一个类型定义:
typedef std::shared_ptr<Container> spContainer;
containers
是一个 std::list
class ObjectsManager : public QObject {
...
public:
spContainer createContainer(QStringList data, QVector2D onMapPosition);
...
private:
std::list<spContainer> containers;
};
使用 QList
或 QVector
时出现同样的错误。
这很奇怪,因为如果我将添加到方法 new QList 并尝试将指针推入容器...
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;
}
它会很好用!
瓦特?有什么区别?!有人可以向我解释发生了什么事吗?
我的错! 问题是我调用了未初始化对象的方法!
修复方法是:
_objManager = spObjectsManager (new ObjectsManager);
_objManager->createContainer(data);