Using RAII to remedy defect where not all code paths performed required exit actions -- Raymond Chen

RaymondChen_5in-150x150.jpgA missing DismissUI() call on one code path led to a subtle bug—but rather than patching it with more try/catch and return logic, there’s a cleaner C++ solution. This article shows how to use RAII and wil::scope_exit to guarantee cleanup across all code paths, even in asynchronous callbacks.

Using RAII to remedy a defect where not all code paths performed required exit actions

by Raymond Chen

From the article:

A team asked me to review their pull request that fixed a bug that was caused by failing to perform some required action along all code paths. Here’s a simplified sketch:

void MySpecialFeature::OnButtonClick()
{
    try {
        auto file = PickFile();
        if (!file) {
            DismissUI();
            return;
        }

        if (ConfirmAction()) {
            if (m_useAlgorithm1) {
                // StartAlgorithm1 invokes the lambda when finished.
                StartAlgorithm1(file, [self = shared_from_this()] {
                    self->DismissUI();
                });
            } else {
                RunAlgorithm2(file);
                DismissUI();
            }
        } else { // this block was missing
           DismissUI(); 
        } 
    } catch (...) {
        DismissUI();
    }
}

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.