Joe*_*eMo 7 c++ language-lawyer
我遇到了这段优雅的代码,然而,它依赖于一个模糊但基本的低级特征:
std::string file_path_leaf( std::string const & path )
{
auto const pos = path.find_last_of("/\\"); // windows or posix
return path.substr( pos + 1 ); // a walk on the wild side?
}
Run Code Online (Sandbox Code Playgroud)
在边缘情况下('find_last_of'失败),它正常工作,即它只留下字符串.但它太模糊了吗?
根据http://en.cppreference.com/w/cpp/string/basic_string/npos npos实际上是这样的...a special value equal to the maximum value representable by the type size_type.使用C++ 11标准进行交叉检查,您可以在21.4/5(类定义)中找到这个拼写.
然后,无标符算法同样由标准保证包围,因此代码完全定义良好.
那说你仍然可以为改变它做出明确的论据.至少添加一条评论,说明它如何为未来的维护者工作.