commit fdf324fe1f9d21b2317ccb0f1c85e2f312074b97
parent 810dba75ff38617ad8915db6ef0d8cdec4b9f7e7
Author: Michael Savage <mikejsavage@gmail.com>
Date: Thu, 24 Jan 2019 07:06:10 +0200
defer instead of SCOPE_EXIT
Diffstat:
4 files changed, 11 insertions(+), 10 deletions(-)
diff --git a/http.cc b/http.cc
@@ -16,7 +16,7 @@ GetResult http_get( const NetAddress & addr, const char * host, const char * pat
if( !net_new_tcp( &sock, addr, NET_BLOCKING ) ) {
return GET_ERROR_CANT_CONNECT;
}
- SCOPE_EXIT( net_destroy( &sock ) );
+ defer { net_destroy( &sock ); };
// TODO: should just be a dynamic string
char request[ 1024 ];
diff --git a/intrinsics.h b/intrinsics.h
@@ -162,11 +162,12 @@ struct ScopeExit {
F f;
};
-template< typename F >
-inline ScopeExit< F > MakeScopeExit( F f ) {
- return ScopeExit< F >( f );
+struct DeferHelper {
+ template< typename F >
+ ScopeExit< F > operator+( F f ) { return f; }
};
-#define SCOPE_EXIT( code ) auto COUNTER_NAME( SCOPE_EXIT_ ) = MakeScopeExit( [&]() { code; } )
+
+#define defer const auto & COUNTER_NAME( DEFER_ ) = DeferHelper() + [&]()
template< typename S, typename T >
struct SameType {
diff --git a/launcher/main.cc b/launcher/main.cc
@@ -208,7 +208,7 @@ static bool already_downloaded( const std::string & path, const ManifestEntry &
FILE * file = fopen( path.c_str(), "rb" );
if( file == NULL )
return false;
- SCOPE_EXIT( fclose( file ) );
+ defer { fclose( file ); };
fseek( file, 0, SEEK_END );
u32 file_size = checked_cast< u32 >( ftell( file ) );
@@ -218,7 +218,7 @@ static bool already_downloaded( const std::string & path, const ManifestEntry &
return false;
void * contents = malloc( file_size );
- SCOPE_EXIT( free( contents ) );
+ defer { free( contents ); };
size_t bytes_read = fread( contents, 1, file_size, file );
if( bytes_read != file_size )
@@ -504,7 +504,7 @@ static void set_registry_key( HKEY hkey, const char * path, const char * value,
WARN( "couldn't open registry key {} {} ({})", path, value, ok_open );
return;
}
- SCOPE_EXIT( RegCloseKey( key ) );
+ defer { RegCloseKey( key ); };
LONG ok_set = RegSetValueExA( key, value, 0, REG_SZ, ( const BYTE * ) data, checked_cast< DWORD >( strlen( data ) + 1 ) );
if( ok_set != ERROR_SUCCESS ) {
@@ -519,7 +519,7 @@ static void set_registry_key( HKEY hkey, const char * path, const char * value,
WARN( "couldn't open registry key {} {} ({})", path, value, ok_open );
return;
}
- SCOPE_EXIT( RegCloseKey( key ) );
+ defer { RegCloseKey( key ); };
LONG ok_set = RegSetValueExA( key, value, 0, REG_DWORD, ( const BYTE * ) &data, sizeof( data ) );
if( ok_set != ERROR_SUCCESS ) {
diff --git a/locked.h b/locked.h
@@ -30,4 +30,4 @@ private:
Mutex mutex;
};
-#define SCOPED_ACQUIRE( locked ) locked.acquire(); SCOPE_EXIT( locked.release(); )
+#define SCOPED_ACQUIRE( locked ) locked.acquire(); defer { locked.release(); }