简体   繁体   中英

Segmentation fault when accessing QSharedPointer object

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.

You cannot instantiate more than one object of shared_ptr ( QSharedPointer ) by the same pointer. In that case the first destroyed shared pointer also destroys owned object.

Only one shared pointer should be initialized by real pointer. Then to copy that pointer a new shared pointer should be initialized by another shared pointer that owns the object.

Here the class CMain should keep QSharedPointer<Nav> instead of pure pointer. The getter should give a copy of that QSharedPointer . In that case the object Nav will be destroyed only when the last its owner QSharedPointer will be destroyed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM