Created
September 21, 2010 14:40
-
-
Save gintenlabo/589772 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <memory> | |
#include <utility> | |
#include <functional> // for std::bind | |
// pointer, deleter のペアから unique_ptr を作る | |
// 本当は不適切( D に pointer の typedef があった場合など) | |
template< class T, class D >// = std::default_delete<T> は VC++ 対応のため泣く泣く削除 | |
inline std::unique_ptr<T, D> to_unique( T* p, D d = D() ) | |
{ | |
return std::unique_ptr<T, D>( p, std::forward<D>(d) ); | |
} | |
// 実装本体 | |
template<class F> | |
inline auto scope_exit( F f ) | |
-> decltype( to_unique( (void*)0, std::bind( std::forward<F>(f) ) ) ) | |
{ | |
void* const p = reinterpret_cast<void*>(666); // 特に意味のない値。 NULL でなければよい | |
return to_unique( p, std::bind( std::forward<F>(f) ) ); | |
} | |
// テスト | |
void foo() | |
{ | |
std::cout << "start" << std::endl; | |
auto const _ = scope_exit( [](){ std::cout << "scope end" << std::endl; } ); | |
std::cout << "end" << std::endl; | |
} | |
void bar() | |
{ | |
std::cout << "start" << std::endl; | |
auto guard = scope_exit( [](){ std::cout << "scope end" << std::endl; } ); | |
std::cout << "end" << std::endl; | |
guard.release(); | |
} | |
int main() | |
{ | |
foo(); | |
std::cout << std::endl; | |
bar(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://gist.github.com/589728 の unique_ptr を使った改善案…だが複雑さを考えると悪くなってる気が。