A
A
ADRian2016-02-16 22:50:53
Qt
ADRian, 2016-02-16 22:50:53

How to do try finally in C++?

Microsoft Visual C++ and CBuilder have __finally.
Is there such a thing from Qt or GNU C++?
How in general it is possible to write such without finally?

class SampleLoader : public QObject
{
    Q_OBJECT
public:
    explicit SampleLoader(QObject *parent = 0);
    void load(QString sampleParameter);
 
signals:
    void workBeginEvent(int stepsCount);
    void workEvent(int step);
    void workEndEvent(bool sampleResult);
 
public slots:
};
 
void SampleLoader::load(QString sampleParameter)
{
    int count = 10;
    bool someResult = false;
    emit workBeginEvent(count);
    try 
    {
        for(int i = 0; i < count; i++)
        {
            QTest::qSleep(100); // hard work
            emit workEvent(i);
        }
        someResult = true;
    }
    finally
    {
        emit workEndEvent(someResult);
    }
}

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
Vitaly, 2016-02-17
@vt4a2h

No, because in C ++ there is no finally according to the standard, which means that sugar from MS and CB is not portable, incl. my advice is not to use it. The usual try-catch is enough for the eyes, incl. read how to use it simply, here for example: www.cplusplus.com/doc/tutorial/exceptions

P
Pavel K, 2016-02-17
@PavelK

What is the inconvenience?
Write after catch(...) {} ...

J
Jacob E, 2016-02-17
@Zifix

There is no need to throw exceptions in C++, especially for such trivial situations. They are slow and dangerous here, Qt does quite well without them.

P
PVRG, 2020-08-04
@PVRG

In c++, not even in MS and BC, finally work fine. This technology is hardwired into the base of the language. Thanks to it, you know that any destructors of static objects of local variables will be called at the end of the blocks where they are defined. If "Ostrich" is finally available, then you can use it. Define a class with the desired destructor code in your code in the destructor describe what should be in the finally. The solution is ugly. But there's nothing you can do about it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question