这个问题是关于只找到没有太多样板代码的解决方案-虽然这可能会生成一些基于意见的解决方案-我真的只是在寻找任何解决方案(没有太多样板代码)
以下内容使我有些头疼-尽管我可以轻松解决此问题,但我想避免过多的样板代码。以下不是合法的c ++,但显示了意图。
char* newBuffer(const char* filename)
{
auto fm = try { //<--try is not legal here
boost::interprocess::file_mapping(filename, boost::interprocess::read_only);
}
catch (boost::interprocess::interprocess__exception& e) {
//report error
return nullptr;//<--this actually makes matters worse since now we cannot just simply wrap in a simpel lambda or function..
}
//rest of function ...
}
我可以将尝试移到函数的开头,但这将意味着try
整个函数(不好的做法),而不仅仅是try
'ingfile_mapping
构造函数。您将如何解决这个难题,并避免在整个函数周围进行try-block?样板代码越少越好。
在出现故障的情况下,任何答案也应解决返回nullptr的问题。
通常,您可以在try块之外声明变量:
boost::interprocess::file_mapping fm;
try {
fm = boost::interprocess::file_mapping(filename, boost::interprocess::read_only);
} catch (boost::interprocess::interprocess__exception& e) {
// Handle error
return nullptr;
}
这要求类型至少是可移动的。
您可以从lambda返回它,但随后必须返回astd::optional
或类似值以指示错误情况,或引发另一个异常。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句