简体   繁体   中英

How can I delete a QSharedPointer

I have written a wrapper around QTextEdit to use it like a QIODevice. I want to be able to use multiple wrapper with the same QTextEdit, so I may use different text color with each wrapper.

To make this wrapper thread-safe I added a QMutex to protect the usage of the QTextEdit. But I was thinking that I must use only one mutex to protect one QTextEdit.

I end up with the following implementation, using a QSharedPointer to protect QTextEdit.

texteditiodevice.h

class TextEditIODevice : public QIODevice
{
    Q_OBJECT

public:
    TextEditIODevice(QTextEdit * qTextEdit, QColor color, QObject * parent);

    virtual ~TextEditIODevice();

protected:
    qint64 readData(char *data, qint64 maxlen);

    qint64 writeData(const char *data, qint64 len);

private:
    /**
     * @brief Pointer to QTextEdit
     */
    QPointer<QTextEdit> textEdit;

    /**
     * @brief Text color
     */
    QColor color;

    /**
     * @brief Shared pointer to QTextEdit associated mutex
     */
    QSharedPointer<QMutex> mutex;

    /**
     * @brief Storage for QTextEdit associated mutexes
     */
    static QMap<QPointer<QTextEdit>, QSharedPointer<QMutex>> mutexes;
};

texteditiodevice.cpp

QMap<QPointer<QTextEdit>, QSharedPointer<QMutex>> TextEditIODevice::mutexes;

TextEditIODevice::TextEditIODevice(QTextEdit * qTextEdit, QColor color, QObject * parent) :
    QIODevice(parent),
    textEdit(qTextEdit),
    color(color)
{
    open(QIODevice::WriteOnly | QIODevice::Text);

    qRegisterMetaType<QTextCharFormat>("QTextCharFormat");
    qRegisterMetaType<QTextBlock>("QTextBlock");
    qRegisterMetaType<QTextCursor>("QTextCursor");

    if(mutexes.contains(textEdit))
        mutex = mutexes[textEdit];
    else
    {
        mutex = QSharedPointer<QMutex>(new QMutex());
        mutexes.insert(textEdit, mutex);
    }
}

TextEditIODevice::~TextEditIODevice()
{
}

qint64 TextEditIODevice::readData(char *data, qint64 maxlen)
{
    Q_UNUSED(data);
    Q_UNUSED(maxlen);
    return 0;
}



qint64 TextEditIODevice::writeData(const char *data, qint64 len)
{
    if(textEdit)
    {
        mutex->lock();
        const QColor lastColor = textEdit->textColor();
        textEdit->setTextColor(color);
        textEdit->append(QString(data));
        textEdit->setTextColor(lastColor);
        mutex->unlock();
    }

    return len;
}

I want to know where I can remove QSharedPointer instance from mutexes mapping so the QMutex will be deleted.

Thanks for your help

As long as the shared pointer is in static mutexes map, it will never be deallocated, and the lifetime of mutexes is the lifetime of the program.

If you want to actually delete a mutex, you have to remove it from the mutexes mapping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM