use*_*807 -2 c++ vector try-catch undeclared-identifier
这是我的代码片段,显示try-catch块中的向量声明:
try {
vector<opClass> op;
}
catch (bad_alloc xa) {
cout << "\nAllocation failure!\n";
return 1;
};
//...
//...
op.push_back(<input some stuff>) //error c2065: op undeclared identifier
Run Code Online (Sandbox Code Playgroud)
奇怪的是,当我将我的矢量声明放在try-catch块之外时,错误消失了.这与STL中如何定义向量有关吗?我认为将这个声明放在try-catch块中是好的做法,因为向量是动态数组?
阿try块定义一个范围.范围内声明的任何内容都不能在该范围之外使用.这与此无关vector,它适用于任何类型的对象.该解决方案是不动之外声明try块,它是将一切到了try块.
try {
vector<opClass> op;
//...
//...
op.push_back(<input some stuff>)
}
catch (bad_alloc xa) {
cout << "\nAllocation failure!\n";
return 1;
}
Run Code Online (Sandbox Code Playgroud)