참고 : http://www.nuonsoft.com/blog/2009/06/09/safeint-in-visual-c-2010/

VS2010에 추가된 라이브러리, 정수형 연산시에 오버플로우 확인이나 나눗셈시에 0으로 나누는 값 확인에 사용될 수 있다.
실제 아래 소스의 결과를 보면 연산 결과가 오버플로우시에는 결과값이 0으로 출력되며 이때 연산중에 SafeIntOnOverflow() 함수가 실행되는 것을 볼 수 있다.
또한 나눗셈 연산 시에도 나누는 값이 0이라면 연산시에 SafeIntOnDivZero() 함수가 호출되는 것을 볼 수 있다.
using namespace std;
using namespace msl::utilities;

class CMySafeIntException : public SafeIntException
{
public:
static void CMySafeIntException::SafeIntOnOverflow()
{
cout << "Caught a SafeInt Overflow exception!" << endl;
}

static void CMySafeIntException::SafeIntOnDivZero()
{
cout << "Caught a SafeInt Divide By Zero exception!" << endl;
}
};

int _tmain(int argc, _TCHAR* argv[])
{
while (1)
{
unsigned int a, b;
cout << "Enter a first 8-bit unsigned integer: ";
cin >> a;
cin.ignore();
cout << "Enter a second 8-bit unsigned integer: ";
cin >> b;
cin.ignore();

// Add both integers
cout << "Adding both numbers as 8-bit integers:" << endl;

// Add both integers using normal operators
unsigned __int8 i1 = a;
unsigned __int8 i2 = b;
cout << "    Using standard operators, result=";
unsigned __int8 iResult = i1 + i2;
cout << (int)iResult << endl;

// Add both integers using SafeInt objects
SafeInt<unsigned __int8, CMySafeIntException> si1(i1);
SafeInt<unsigned __int8, CMySafeIntException> si2(i2);
cout << "    Using SafeInt objects, result=";
SafeInt<unsigned __int8, CMySafeIntException> siResult = si1 + si2;
cout << (int)siResult << endl;

// Divide both integers
cout << endl << "Dividing both numbers:" << endl;

// Divide both integers using normal operators
cout << "    Using standard operators, result=";
if (i2 != 0)// Prevent a crash!
{
iResult = i1 / i2;
cout << (int)iResult << endl;
}
else
cout << "Aborting because divide by zero." << endl;

// Divide both integers using SafeInt objects
cout << "    Using SafeInt objects, result=";
siResult = si1 / si2;
cout << (int)siResult << endl;

cout << endl << endl;
}

return 0;
}

결과:

사용자 삽입 이미지

Related Posts

답글 남기기

이메일 주소는 공개되지 않습니다.