C ++ Syntax Syntax

I have a general question regarding the throwing syntax of an object. Consider:

#include <stdio.h> struct bad { }; void func() { throw bad; } int main(int, char**) { try { func(); } catch(bad) { printf("Caught\n"); } return 0; } 

This code does not compile (g ++ 4.4.3), since the string 'throw' should be replaced by:

 throw bad(); 

Why is this? If I create a bad stack, I create it like this:

 bad b; // I can't use 'bad b();' as it is mistaken for a function prototype 

I consulted Straustup's book (and this site), but could not find any explanation for what seemed inconsistent to me.

+6
source share
3 answers
 throw bad; 

does not work, because bad is a data type, structure ( struct bad ). You cannot throw away a data type, you need to throw away an object that is an instance of a data type.

You need to do:

 bad obj; throw obj; 

because it creates an obj object of the bad structure and then throws that object away.

+9
source

You need to throw an instance of the structure.

 void func() { bad b; throw b; } 
+2
source

The difference is that the throw argument is an object, not a type. Declaring a variable as bad b has the syntax [type] [object_name]; . And enter! = Instance.

0
source

Source: https://habr.com/ru/post/901552/


All Articles