项目健壮性提升方案 folly::tryTo代替std::stoll

项目之前使用的方案,代码中使用std::stoll实现stringint转换uint64_t型,如果是用户侧参数,存在不可信任问题,一旦参数为不合法数字型字符串或者空,都会存在stoll无法转化问题,而且会导致项目coredump出现。

#include
#include
 
int main()
{
  long long num;
  string str = "asb"; //coredump
  //string str = ""; //coredump
  num = std::stoll(str);
  std::cout << num <<  std::endl;

  return 0;
} 

 

目前完善后的方案,使用folly:tryTo比stoll中实现try-catch更加优雅。

#include 
#include "folly/Conv.h"

int main(int argc, char** argv) {

  auto str_opt = folly::tryTo("sds"); // 不会coredump
  //auto str_opt = folly::tryTo("123123"); 
  if (str_opt.hasValue()) {
    uint64_t temp_str = str_opt.value();
    std::cout << temp_str << std::endl;
  }

  return 0;
}

 

你可能感兴趣的:(C++实战)