中級 › terminate called after throwing an instance of 'std::out_of_range' の原因と直し方 › パターン3
terminate called after throwing an instance of 'std::out_of_range' の原因と直し方
std::vectorの範囲外の要素に .at() でアクセスしたときに、例外std::out_of_rangeが投げられ、それを捕まえずにプログラムが終了してしまうバグです。
1 #include <iostream> 2 #include <vector> 3 int main() { 4 std::vector<int> items = {5, 10}; 5 std::cout << items.at(__) << std::endl; ^ 6 return 0; 7 }
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 7) >= this->size() (which is 2)
Aborted
空欄を埋めてコンパイル・実行を通す
operator[]と違い、.at()は範囲チェックのコストと引き換えに安全な例外を保証します。捕まえずに使うと未捕捉例外でプロセスが落ちます。
次の問題