2014-10-21

C++でfinally

一部の言語には、finallyという機能がある。あるブロックスコープを抜ける時に、必ず実行される処理を記述することが出来る。


try {
    // 処理
}
finally {
    // ブロック文を抜けた時に必ず実行される処理
}

C++にfinallyがない理由は、特に専用の文法が必要なく、ライブラリで十分なためだ。デストラクターとlambda式を使えばよい。

class scoped_guard
{
    std::function< void() > f ;
public :
    explicit scoped_guard( std::function< void () > f )
        : f(f) { }

    scoped_guard( scoped_guard const & ) = delete ;
    void operator = ( scoped_guard const & ) = delete ;


    ~scoped_guard()
    { f() ; }

} ;


int main()
{
    
    {
        scoped_guard guard( []{ /* ブロック文を抜けた時に必ず実行される処理 */ } ) ;
        // 処理
    }
}

ちなみに、これをもう少し汎用的に設計したものが、標準ライブラリに提案されている。

N3949: Scoped Resource - Generic RAII Wrapper for the Standard Library

ドワンゴ広告

この記事はドワンゴ勤務中に書かれた。

ドワンゴは本物のC++プログラマーを募集しています。

採用情報|株式会社ドワンゴ

CC BY-ND 4.0: Creative Commons — Attribution-NoDerivatives 4.0 International — CC BY-ND 4.0

No comments: