Namespaces
Variants

std:: out_of_range

From cppreference.net
定义于头文件 <stdexcept>
class out_of_range ;

定义一种作为异常抛出的对象类型。它报告因试图访问超出定义范围的元素而导致的错误。

它可能由 std::bitset std::basic_string 的成员函数、 std::stoi std::stod 系列函数,以及进行边界检查的成员访问函数(例如 std::vector::at std::map::at )抛出。

std::out_of_range 的所有成员函数均为 constexpr :可以在常量表达式求值过程中创建和使用 std::out_of_range 对象。

std::out_of_range 对象通常不能是 constexpr ,因为任何动态分配的存储都必须在同一常量表达式求值过程中释放。

(since C++26)
cpp/error/exception cpp/error/logic error std-out of range-inheritance.svg

继承关系图

目录

成员函数

(constructor)
使用给定消息构造新的 out_of_range 对象
(公开成员函数)
operator=
替换 out_of_range 对象
(公开成员函数)

std::out_of_range:: out_of_range

out_of_range ( const std:: string & what_arg ) ;
(1) (constexpr since C++26)
out_of_range ( const char * what_arg ) ;
(2) (constexpr since C++26)
out_of_range ( const out_of_range & other ) ;
(3) (noexcept since C++11)
(constexpr since C++26)
1) 使用 what_arg 作为解释字符串构造异常对象。构造后满足 std:: strcmp ( what ( ) , what_arg. c_str ( ) ) == 0
2) 使用 what_arg 作为解释字符串构造异常对象。构造后满足 std:: strcmp ( what ( ) , what_arg ) == 0
3) 拷贝构造函数。如果 * this other 都具有动态类型 std::out_of_range ,则满足 std:: strcmp ( what ( ) , other. what ( ) ) == 0 。拷贝构造函数不会抛出任何异常。

参数

what_arg - 解释性字符串
other - 要复制的另一个异常对象

异常

1,2) 可能抛出 std::bad_alloc

注解

由于不允许在复制 std::out_of_range 时抛出异常,该消息通常内部存储为单独分配的引用计数字符串。这也是为什么没有接受 std::string&& 的构造函数的原因:无论如何都需要复制内容。

LWG issue 254 解决之前,非拷贝构造函数只能接受 std::string 。这使得在构造 std::string 对象时必须进行动态分配。

LWG issue 471 解决之后,派生的标准异常类必须具有可公开访问的拷贝构造函数。只要原始对象和复制对象通过 what() 获得的解释字符串相同,该构造函数可以隐式定义。

std::out_of_range:: operator=

out_of_range & operator = ( const out_of_range & other ) ;
(noexcept since C++11)
(constexpr since C++26)

使用 other 的内容进行赋值。如果 * this other 都具有动态类型 std::out_of_range ,则赋值后 std:: strcmp ( what ( ) , other. what ( ) ) == 0 。复制赋值运算符不会抛出任何异常。

参数

other - 用于赋值的另一个异常对象

返回值

* this

注解

LWG issue 471 决议后,派生的标准异常类必须具有可公开访问的复制赋值运算符。只要原始对象和复制对象通过 what() 获得的说明字符串相同,该运算符可以隐式定义。

继承自 std:: exception

成员函数

[virtual]
销毁异常对象
( std::exception 的虚公开成员函数)
[virtual]
返回说明性字符串
( std::exception 的虚公开成员函数)

注释

标准错误条件 std::errc::result_out_of_range 通常表示结果(而非输入)超出范围的情况,与 std::range_error ERANGE 具有更紧密的关联性。

功能测试 标准 功能
__cpp_lib_constexpr_exceptions 202502L (C++26) constexpr 异常类型

缺陷报告

下列行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

缺陷报告 适用标准 发布时行为 正确行为
LWG 254 C++98 缺少接受 const char * 的构造函数 已添加
LWG 471 C++98 std::out_of_range 副本的说明字符串
由实现定义
与原始 std::out_of_range 对象
的说明字符串相同

参阅

访问指定字符(带边界检查)
( std::basic_string<CharT,Traits,Allocator> 的公开成员函数)
访问指定字符(带边界检查)
( std::basic_string_view<CharT,Traits> 的公开成员函数)
访问指定元素(带边界检查)
( std::deque<T,Allocator> 的公开成员函数)
访问指定元素(带边界检查)
( std::map<Key,T,Compare,Allocator> 的公开成员函数)
访问指定元素(带边界检查)
( std::unordered_map<Key,T,Hash,KeyEqual,Allocator> 的公开成员函数)
访问指定元素(带边界检查)
( std::vector<T,Allocator> 的公开成员函数)
访问指定元素(带边界检查)
( std::array<T,N> 的公开成员函数)
(C++26)
访问指定元素(带边界检查)
( std::span<T,Extent> 的公开成员函数)