我一直在努力了解如何将其作为常量引用传递。
我有以下类(class):
class DBContext : public QObject
在我的类 MainWindow 中,我将其定义如下:
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>'中声明的私有(private)成员
更新
获取使用 QSharedPointer 和 QWeakPointer 的技巧。这是使用这两个指针的有效方法吗?另外,我是否在 A 类和 B 类上都正确使用了 clear()?
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
的范围联系起来。如果您可以分配/复制它,那么它就打败了整点。
关于c++ - 了解通过引用传递的 QScopedPointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33793633/