避免默认参数异常
Avoiding exceptions in default parameters
我有一个这样的函数声明:
void foo(std::string const &bar = std::string(""));
现在,我们正在使用 MISRA C++,我们的代码验证器在默认值的构造函数上给出了一个错误:
RULE 15-5-3: The terminate() function shall not be called implicitly.
我知道在创建默认参数的某个地方可能有一个字符串构造(一个明智的编译器无疑会优化它,但 MISRA C++ 的规则也涵盖了愚蠢的编译器),也就是说,可以翻译:
foo();
至
std::string tmp(std::string("")); // May run out of memory, etc
foo(tmp);
但是,有什么办法可以解决这个问题,除了显而易见的:
void foo(std::string const &bar);
void foo() { foo(std::string("")); }
这可能会因为多个可选参数而变得混乱,但是...
尝试在函数声明之外初始化默认参数:
const std::string def = "";
...
void foo(std::string const &bar = def);
我有一个这样的函数声明:
void foo(std::string const &bar = std::string(""));
现在,我们正在使用 MISRA C++,我们的代码验证器在默认值的构造函数上给出了一个错误:
RULE 15-5-3: The terminate() function shall not be called implicitly.
我知道在创建默认参数的某个地方可能有一个字符串构造(一个明智的编译器无疑会优化它,但 MISRA C++ 的规则也涵盖了愚蠢的编译器),也就是说,可以翻译:
foo();
至
std::string tmp(std::string("")); // May run out of memory, etc
foo(tmp);
但是,有什么办法可以解决这个问题,除了显而易见的:
void foo(std::string const &bar);
void foo() { foo(std::string("")); }
这可能会因为多个可选参数而变得混乱,但是...
尝试在函数声明之外初始化默认参数:
const std::string def = "";
...
void foo(std::string const &bar = def);