I have written a small sample application code as below.
#include <QCoreApplication>
#include <QSharedPointer>
#include <QDebug>
class INav
{
public:
virtual int getdata() = 0;
virtual void setdata(int a) = 0;
};
class Nav : public INav
{
int i;
public:
Nav(int a) : i(a) {}
int getdata() { return i;}
void setdata(int a) { i = a; }
};
class CMain
{
Nav* nav;
public:
CMain(Nav* n) : nav(n) {}
QSharedPointer<INav> getINav()
{
QSharedPointer<Nav> n(nav);
return n.staticCast<INav>();
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSharedPointer<CMain> m(new CMain(new Nav(1)));
int i = 0;
while (++i != 3)
{
QSharedPointer<INav> nav = m->getINav();
qDebug() << nav.data()->getdata();
}
return a.exec();
}
when I will print the debug message second time it shows the segmentation fault and application crashes. As per the documentation of QSharedPointer, it might be deleting the pointer first time after accessing the element.
I want QSharedPointer nav = m->getINav(); to be in while loop itself as this is kind of dummy application for my real scenario problem.
I am not sure how to make this works, any help will be appreciated. Thanks In advance.