0
第一次调用函数时,我的印象是函数作用域非窗格结构初始化为 。然而,在VS-2010中,如果构造函数抛出异常,构造函数每次被调用,直到构建成功为止。函数作用域静态非窗格对象初始化
此行为实现是特定的还是标准保证的内容?
下面是人为的例子展示的行为:
#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;
}
输出:
迭代:0
分配资源
静态对象构造
免费资源
捕捉到异常:错误
迭代:1
分配资源
静态对象构造
免费资源
捕捉到异常:错误
迭代:2
分配资源
静态对象构造
免费资源
捕捉到异常:错误**
谢谢你有道理,所以我想这种行为是不是编译器特定? – keety 2012-04-25 00:43:17
@ keety:正确的,这个行为是由C++标准强制的。 – ildjarn 2012-04-25 01:34:59