Zero template with QObject

(C ++ / Qt) I have a smart pointer to a QObject. Say QWeakPointer. For some external reason (something that might happen in another object or due to an event), it is possible that the pointed object will be destroyed. Since I have a smart pointer, there will be no dangling links, so there is no problem. But I always need to check if the pointer is null or not.

I am thinking of using a null pattern so as not to check this all the time, but I'm not sure if this is possible or convenient with QObject. The idea would be that the pointer points to an object, and if it is destroyed, the smart pointer changes its pointed object to a null object. Is this a good idea, or should I forget it and just check if the pointer is NULL all the time?


Let us show you an example. We have a worker who uses a tool to do his job:

class Worker : public QObject
{
    Q_OBJECT

public:
    Worker(QObject *parent = 0);
    void work()
    {
        if(m_tool)
            m_tool->use();
        emit workCompleted();
    };

signals:
    workCompleted();

public slots:
    void setTool(QWeakPointer<Tool> tool);

private:
    QWeakPointer<Tool> m_tool;
};


class Tool : public QObject
{
    Q_OBJECT

public:
    Tool();

public slots:
    void use() =0;
};


class Screwdriver : public Tool
{
    Q_OBJECT

public:
    Screwdriver() : Tool();

public slots:
    void use()
    {
        // do something
    };
};


class Hammer : public Tool;
class Saw : public Tool;
...

In this case, the Tool is an object of the public domain of the library that is used by Worker. I am developing such a library. Thus, the worker uses a screwdriver, but he collapses and collapses. No problems:

if(m_tool)
    m_tool->use();
emit workCompleted();

m_tool = 0, so it just does nothing. But we have to check that it is not zero every time.

Now let's say that we had a NullTool object:

class NullTool : public Tool
{
    Q_OBJECT

public:
    NullTool() : Tool();

public slots:
    void use()
    {
        // does nothing
    };
};

When the tool was destroyed, our pointer would be smart and know that it should point to a NullTool instance. Therefore, Worker :: work () can be implemented as follows:

void Worker::work()
{
    m_tool->use();
    emit workCompleted();
};

m_tool-> use () is then called in NullTool, which does nothing, so there is no need to check that the pointer is not null.

? Qt, QWeakPointer?

+3
3

, , . , QString QVariant, if (str & &! Str- > isEmpty()), if (! Str.isEmpty()). QObjects, , "", .

+3

, , , QObject:

void destroyed ( QObject * obj = 0 );
0

. , , . 10.000 . : , Tool::use() .

, Tool::use() , NullTool::use(). : , .

0

Source: https://habr.com/ru/post/1762417/


All Articles