Search code examples
c++qtqsharedpointerqscopedpointer

Understanding QScopedPointer passing by reference


I've been trying to understand how to pass this as a const reference.

I have the following class:

class DBContext : public QObject

In my class MainWindow I define it as folows:

private:
    QScopedPointer<DBContext> dbContext;

How Storage class is defined:

class StorageData : public QObject
{
    Q_OBJECT

public:
    StorageData(QObject *parent = 0);
    ~StorageData();

    void SetDBContext(const QScopedPointer<DBContext> &db_context);

private:
    QScopedPointer<DBContext> dbContext;

In StorageData SetDBContext() I try to assign it with the following:

void StorageData::SetDBContext(const QScopedPointer<DBContext> &db_context)
{
    dbContext = db_context;
}

Then in the MainWindow constructor initialize it:

dbContext.reset(new DBContext(this));
StorageData storage;
storage.SetDBContext(dbContext);

Using the following in StorageData function SetDBContext():

_DBContext = db_context; 

I get an error:

'QScopedPointer>::operator =' : cannot access private member declared in class 'QScopedPointer>'

Update

Taking the tip of using QSharedPointer and QWeakPointer. Is this a valid approach of using these two pointers? Also am I using clear() correctly on both Class A & B?

class A
private:
  QWeakPointer<DBContext> dbContext;

void A::~A()
{
     dbContext.clear()
}
void A::SetDBContext(QWeakPointer<DBContext> db_context)
{
    dbContext= db_context;
}

void A::UseCode()
{
    QSharedPointer<DBContext> ptrContext= dbContext.toStrongRef();
    ..
}

class B constructor:
private:
    QSharedPointer<DBContext> dbContext; 

In the constructor:

B::B()
{
    dbContext.reset(new DBContext(this));
    QWeakPointer<DBContext> ptrDBConnect = dbContext;
    storage.SetDBContext(ptrDBConnect);
}

In the destructor:

B::~B()
{
    dbContext.clear();
}

Solution

  • From the documentation on QScopedPointer:

    QScopedPointer intentionally has no copy constructor or assignment operator, such that ownership and lifetime is clearly communicated.

    The purpose of QScopedPointer is to keep the lifetime of the object you are pointing to tied to the scope of the QScopedPointer. If you could assign/copy it, then it defeats the whole point.