2009年5月19日火曜日

boost::scope_exit で戻り値変更

 boost/scope_exit を使って、トランザクションのコミットとロールバックを制御し、コミットが成功したかどうかを更に返したいと思って、スクラッチを書いてみた。もうちょいスマートに書けないものかなー。

#include <boost/scope_exit.hpp>
#include <iostream>

int scope_test() {
  int res = 0;
  std::cout << "scope_test" << std::endl;
  BOOST_SCOPE_EXIT( (&res) ) {
    std::cout << "boost scope exit work!" << std::endl;
    res = 3;
  }
  BOOST_SCOPE_EXIT_END
  std::cout << "scope_test: res = " << res << std::endl;
  return res;
}

int scope_test2( int success ) {
  int res = 0;
  std::cout << "scope_test2" << std::endl;
  while(1) {
    BOOST_SCOPE_EXIT( (&res) ) {
      if( !res ) { // success case
        std::cout << "Something to Commit." << std::endl;
        std::cout << "But fail to Commit, and reset result." << std::endl;
        res = 3;
      } else {  // fail case
        std::cout << "Something to Rollback." << std::endl;
      }
    }
    BOOST_SCOPE_EXIT_END
    if( !success ) {
      std::cout << "FAIL" << std::endl;
      res = 1;
      break;
    }
    std::cout << "SUCCESS" << std::endl;
    break;
  }
  return res;
}


int main() {
  std::cout << "result of scope_test = " << scope_test() << std::endl;
  std::cout << "------------------------------" << std::endl;
  std::cout << "result of scope_test(SUCCESS) = " << scope_test2( 1 ) << std::endl;
  std::cout << "------------------------------" << std::endl;
  std::cout << "result of scope_test(FAIL) = " << scope_test2( 0 ) << std::endl;

return 0;
}


追記:
Class の Member function 中から、終了時に Class の Member function をコールしたい場合の擬似コードは
void Foo::bar() {
  Foo* this_pointer = this;
  BOOST_SCOPE_EXIT( (this_pointer) ) {
    this_pointer->another_member_function();
  }
  BOOST_SCOPE_EXIT_END
  ...
}

0 件のコメント: