5

I am trying to prevent naked pointers, to prevent memory leaking etc. I also want to map int to INuiSensor*. Since I am also using Qt I tried to use QMap<int, std::unique_ptr<INuiSensor>> to do this, but the source code of QMap makes this impossible:

template <class Key, class T>
Q_INLINE_TEMPLATE typename QMap<Key, T>::iterator QMap<Key, T>::insert(const Key &akey, const T &avalue)
{
    detach();
    Node *n = d->root();
    Node *y = d->end();
    Node *last = 0;
    bool  left = true;
    while (n) {
        y = n;
        if (!qMapLessThanKey(n->key, akey)) {
            last = n;
            left = true;
            n = n->leftNode();
        } else {
            left = false;
            n = n->rightNode();
        }
    }
    if (last && !qMapLessThanKey(akey, last->key)) {
        last->value = avalue;
        return iterator(last);
    }
    Node *z = d->createNode(akey, avalue, y, left);
    return iterator(z);
}

The line:

last->value = avalue;

Is the one that creates the problem: you cannot use the =operator directly on a unique_ptr. So now I am puzzeled on what to do next. Is it possible to use QMap and unique_ptr in some other way? Is the whole idea of using QMap and unique_ptr stupid for some reason? What can I do to prevent using naked pointers while still using a QMap?

4

2 回答 2

2

使用 Qt 容器,您应该使用 Qt 智能指针实现。有关此线程中不同实现的更多信息。

有哪些 C++ 智能指针实现可用?

如前所述,您可以使用 QSharedPointer。

于 2013-04-28T13:56:42.423 回答
-1

当然这是行不通的,你已经创建了一个唯一的指针,然后你尝试将它复制到一个QMap.

使用QSharedPointer. 当对INuiSensor*实例的所有引用都已删除时,该实例将被删除。

于 2013-04-28T13:05:15.890 回答