我最近遇到了这个语法try-catchfor function.
struct A
{
int a;
A (int i) : a(i) // normal syntax
{
try {}
catch(...) {}
}
A () // something different
try : a(0) {}
catch(...) {}
void foo () // normal function
try {}
catch(...) {}
};
Run Code Online (Sandbox Code Playgroud)
两种语法都有效.除了编码风格之外,这些语法之间是否有任何技术差异?在任何方面,语法之一是否优于其他语法?
我想知道程序员何时使用函数try块.什么时候有用?
void f(int i)
try
{
if ( i < 0 )
throw "less than zero";
std::cout << "greater than zero" << std::endl;
}
catch(const char* e)
{
std::cout << e << std::endl;
}
int main() {
f(1);
f(-1);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:(在ideone处)
greater than zero
less than zero
Run Code Online (Sandbox Code Playgroud)
编辑:因为有些人可能认为函数定义的语法不正确(因为语法看起来不熟悉),我要说它不是不正确的.它叫做function-try-block.参见C++标准中的§8.4/ 1 [dcl.fct.def].
这编译,但我从来没有在任何其他代码中看到它.安全吗?
Testclass():sources(new int[32]){}
Run Code Online (Sandbox Code Playgroud)
代替:
Testclass(){
sources = new int[32];
}
Run Code Online (Sandbox Code Playgroud)