3

如何将 QScopedPointer 对象传递给像这样的另一个函数:

bool addChild(QScopedPointer<TreeNodeInterface> content){
   TreeNode* node = new TreeNode(content);
}

树节点:

TreeNode::TreeNode(QScopedPointer<TreeNodeInterface> content)
{
    mContent.reset(content.take());
}

我得到:错误:'QScopedPointer::QScopedPointer(const QScopedPointer&) [with T = TreeNodeInterface; Cleanup = QScopedPointerDeleter]' 是私有的

我该如何解决?谢谢!

4

1 回答 1

3

您可以通过接受对指针的引用来做到这一点 - 这样您就可以将 null 本地指针与传递给您的指针交换:

#include <QScopedPointer>
#include <QDebug>

class T {
   Q_DISABLE_COPY(T)
public:
   T() { qDebug() << "Constructed" << this; }
   ~T() { qDebug() << "Destructed" << this; }
   void act() { qDebug() << "Acting on" << this; }
};

void foo(QScopedPointer<T> & p)
{
   using std::swap;
   QScopedPointer<T> local;
   swap(local, p);
   local->act();
}

int main()
{
   QScopedPointer<T> p(new T);
   foo(p);
   qDebug() << "foo has returned";
   return 0;
}

输出:

Constructed 0x7ff5e9c00220 
Acting on 0x7ff5e9c00220 
Destructed 0x7ff5e9c00220 
foo has returned
于 2015-05-14T15:38:16.153 回答