except13.c

来自「开放源码的编译器open watcom 1.6.0版的源代码」· C语言 代码 · 共 45 行

C
45
字号
#include "fail.h"

int alloc_count;

struct S {
    S( int x ) : x(x) { throw int(x); }
    ~S() { fail(__LINE__); }
    void *operator new( unsigned x ) {
	++alloc_count;
	return malloc( x );
    }
    void operator delete( void *p ) {
	--alloc_count;
	if( alloc_count < 0 ) fail(__LINE__);
	free( p );
    }
    int x;
};

void test( int v )
{
    try {
	S *p = new S(v);
	delete p;
    } catch( int x ) {
	if( x != v ) fail(__LINE__);
	return;
    } catch( ... ) {
	fail(__LINE__);
    }
}

int main()
{
    for( int i = 0; i < 10000; ++i ) {
	test( i );
	if( alloc_count != 0 ) {
	    fail(__LINE__);
	    break;
	}
	if( errors ) break;
    }
    _PASS;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?