Handling Static_Cast Failures

Write your question here.

Is it possible to handle situations where static cast fails.
I have a sample code written below, can someone help me in handling such failures?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  typedef struct test
{
	int a;
	int b;
}tester;

void setevent(void *in)
{
	tester *recv = static_cast<tester*>(in);

	cout << "recv->a: " << recv->a << endl;
             //Seg Fault, how to handle this???
	cout << "recv->b: " << recv->b << endl;
}

int main(int argc, char *argv[])
{
	tester *one = new tester();
	one->a = 10;
	one->b = 20;
	setevent((void *)1);  // setevent((void*)(one))
}


In above code when setevent is called with the tester object, there is no issue, but if we pass random value it leads to seg fault. This is because static_cast is not type_safe, but can it be handled in any other way?
If static_cast fails you will get a compile error and the program executable will never even be built.

Your example has undefined behavior, not a failure or an error. Solution: don't use void *. Just don't. It's only required when working with a C library in some cases. It has no place in C++.
Last edited on
Topic archived. No new replies allowed.