Static initialization of non-POD that throws

O

Old Wolf

In the following code:
1) Is the exception allowed to be thrown even if the
user never enters '1'?
2) If the user enters '1' a second time, what happens?

How does the compiler typically implement all this?

#include <iostream>

int x = 0;

struct S
{
void foo() { std::cout << "In foo" << std::endl; }
S() { if (x++ == 0) throw 1; }
};

int main()
{
while (1) switch( std::cin.get() )
{
case '1': try { static S s; s.foo(); } catch(...) {} break;
case EOF: return 0;
}
}
 
A

anon

Old said:
In the following code:
1) Is the exception allowed to be thrown even if the
user never enters '1'?

Constructors can throw exceptions, but in this case, the construction
will first wait for cin to finish
2) If the user enters '1' a second time, what happens?

Since i is not 0 anymore, nothing will be thrown from the constructor
and the object will be constructed.
Third and fourth and further 1s will not call constructor, because you
declared your object static.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,008
Latest member
HaroldDark

Latest Threads

Top