exit() call inside a function which should return a reference

前端 未结 4 1552
囚心锁ツ
囚心锁ツ 2020-11-27 08:13

In a library I have a function which searches for a key in a database and return a non-const reference to an object. I want to handle the case in which the key is not found,

4条回答
  •  清酒与你
    2020-11-27 08:46

    The answer, as the other respondents, said, should be: throw an exception...

    Type & get(const Key & k) {
         if( !my_db.key_exists(k) ) {
              std::stringstream error;
              error << "key " << k << " not found";
              throw std::runtime_error(error);
         }
         return my_db.at(k);
    }
    

提交回复
热议问题