Reputation: 17441
I was under the impression that Function Scoped Non-Pod structures are intialized the first time the function is invoked. However on VS-2010 it appears if the constructor throws an exception the constructor is invoked each time until a successful construction.
Is this behavior implementation specific or something the standard guarantees ?
Below is contrived example to demonstrate the behaviour :
#include <iostream>
#include <string>
using namespace std;
//dummy resource class
class Resource {
public:
Resource() {
cerr<<"Allocate Resource "<<endl;
}
~Resource() {
cerr<<"Free Resource"<<endl;
}
};
//dummy class which will be statically instantiated
class Dummy {
public:
Dummy() {
cerr<<"in Dummy"<<endl;
throw(string("error"));
}
Resource res;
};
//main program
int main() {
for(int i = 0;i<3;i++) {
try {
//create a static object throw and exception
static Dummy foo;
}
catch ( std::string &e) {
cerr<<"Caught exception:"<<e<<endl<<endl;
}
}
return 1;
}
Output:
Iteration:0
Allocate Resource
Static Object Constructor
Free Resource
Caught exception:error
Iteration:1
Allocate Resource
Static Object Constructor
Free Resource
Caught exception:error
Iteration:2
Allocate Resource
Static Object Constructor
Free Resource
Caught exception:error**
Upvotes: 0
Views: 180
Reputation: 62975
I was under the impression that Function Scoped Non-Pod structures are intialized the first time the function is invoked.
Sure, but think about what 'initialized' means – if the constructor throws, the object is not initialized because there is no object. Consequently, the next time the object declaration is encountered, it will (attempt to) be initialized again.
Upvotes: 4