2014-12-02 :-(
_ 午後
1300 労働
_ [C]最初にアクセスしたときに領域確保する
Singleton ぽいものですがどうですかね。
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> enum { BUFFER_MAX = 8, }; char* buffer = NULL; void errx( void ) { printf( "%s\n", strerror( errno ) ); exit( 1 ); } char* getInstance( void ) { if( buffer == NULL ) { buffer = malloc( BUFFER_MAX ); if( buffer == NULL ) { errx(); } } return buffer; } void destroy( void ) { if( buffer != NULL ) { free( buffer ); } } char read( int index ) { char* buf = getInstance(); return buf[ index ]; } void write( int index, char data ) { char* buf = getInstance(); buf[ index ] = data; } int main(int ac, char** av) { char data; atexit( destroy ); write( 0, 1 ); data = read( 0 ); printf( "%d\n", data ); write( 1, 2 ); data = read( 1 ); printf( "%d\n", data ); return 0; }
$ gcc c.c $ ./a.exe 1 2
オブジェクト指向ムズイっす
デザインパターンも合わせると腑に落ちるます。FactoryパターンとかObserverパターンとか( まあオブジェクト指向じゃなくても実装できるけど )