c – 了解通过引用传递的QScopedPointer

我一直试图理解如何将其作为const引用传递.

我有以下课程:

class DBContext : public QObject

在我的班级MainWindow中,我将其定义为folows:

private:
    QScopedPointer<DBContext> dbContext;

如何定义存储类:

class StorageData : public QObject
{
    Q_OBJECT

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

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

private:
    QScopedPointer<DBContext> dbContext;

在StorageData SetDBContext()中,我尝试使用以下内容进行分配:

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

然后在MainWindow构造函数中初始化它:

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

在StorageData函数SetDBContext()中使用以下内容:

_DBContext = db_context; 

我收到一个错误:

‘QScopedPointer> :: operator =’:无法访问类’QScopedPointer>’中声明的私有成员

更新

采用QSharedPointer和QWeakPointer的提示.这是使用这两个指针的有效方法吗?我也在A类和A类上正确使用clear() 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; 

在构造函数中:

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

在析构函数中:

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

最佳答案 从QScopedPointer的文档:

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

QScopedPointer的目的是使您指向的对象的生命周期与QScopedPointer的范围保持一致.如果你可以分配/复制它,那么它就会失败.

点赞