Cpp:s2095 FP when using scoped objects to close resource

S2095 reports resources that are not closed. It seems to ignore when the resources are closed using scoped objects to close the resource. E.g. a custom written scope_exit.

Example:

class scope_exit {
public:
    using ExitFunc = std::function<void()>;
    
    explicit scope_exit(ExitFunc exitFunc) :
        _exitFunc(std::move(exitFunc)) {
    }

    ~scope_exit() {
        if (_exitFunc) {
            _exitFunc();
        }
    }

    scope_exit(const scope_exit &) = delete;
    scope_exit& operator=(const scope_exit &) = delete;
    scope_exit(scope_exit &&other) noexcept {
        _exitFunc.swap(other._exitFunc);
        other._exitFunc = nullptr;
    } 
    scope_exit& operator=(scope_exit &&other) noexcept {
        if (this != &other) {
            _exitFunc();
            _exitFunc.swap(other._exitFunc);
            other._exitFunc = nullptr;
        }

        return *this;
    }
private:
    ExitFunc _exitFunc;

};

int main() {
    FILE* file = fopen("c:\\temp\\somefile.bin", "rb");
    scope_exit scoped([file] {
        fclose(file);
    });

    return 0;
}

I can see how this is a complex situation to analyze. Is there any way I can modify the scope_exit class to indicate to SonarLint that is in fact handling the resource?

Hello @Tohnmeister,

Thanks for the detailed report.

I was able to reproduce the issue. It is related to the handling of `std::function. I created this ticket CPP-3703 that you can follow.

I’m not sure that changing perfectly fine code to make SonarLint happy is the right approach. Instead, I would recommend:

  • Using connected mode(if you are using SonarQube or SonarCloud). This way you can mark the issue as false-positive on the server and it won’t appear in your IDE.
  • if you cannot use connected mode. I would suggest ignoring the issue and vote-up this under consideration feature: “Mute individual issues on-the-fly in your IDE”.

Thanks,

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.