STL容器判空与指针保护问题

来源:互联网 发布:erp管理系统源码 编辑:程序博客网 时间:2024/06/15 00:03

容器判空

  • 问题:写代码通过CI的cppcheck,检测出性能问题。定位到容器的判断
std::list<T> myList;// some code // 判空if (0 !=  list.size()) {    // dosomething}
  • 原因是,对于std::list,size()的复杂度是O(n),empty的复杂度是O(1)
  • 修改后代码
std::list<T> myList;// some code // 判空if (!list.empty()) {    // dosomething}

指针保护

  • 问题:写代码时,没有对指针判空,就直接调用指针的函数。
function(){    // some code    m_pointer->func();    // some code }
  • 修改后代码如下
function(){    // some code    if ( null != m_pointer) {        m_pointer->func()    }    else {        // some code for pointer is null    }    // some code }

总结

  • 克服小问题,养成好的编码风格。
原创粉丝点击