命名空间
变体
操作

std::length_error

来自 cppreference.cn
< cpp‎ | error
定义于头文件 <stdexcept>
class length_error;

定义作为异常抛出的对象类型。它报告因尝试超出某些对象的实现定义长度限制而导致的错误。

此异常由 std::basic_stringstd::vector::reserve 的成员函数抛出。

cpp/error/exceptioncpp/error/logic errorstd-length error-inheritance.svg

继承关系图

目录

[编辑] 成员函数

(构造函数)
构造一个新的 length_error 对象,带有给定的消息
(公共成员函数)
operator=
替换 length_error 对象
(公共成员函数)

std::length_error::length_error

length_error( const std::string& what_arg );
(1)
length_error( const char* what_arg );
(2)
length_error( const length_error& other );
(3) (noexcept since C++11) (C++11 起无异常抛出)
1) 构造异常对象,使用 what_arg 作为解释性字符串。构造后,std::strcmp(what(), what_arg.c_str()) == 0
2) 构造异常对象,使用 what_arg 作为解释性字符串。构造后,std::strcmp(what(), what_arg) == 0
3) 复制构造函数。如果 *thisother 都具有动态类型 std::length_error,则 std::strcmp(what(), other.what()) == 0。复制构造函数不抛出任何异常。

参数

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

异常

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

注解

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

LWG issue 254 决议之前,非复制构造函数只能接受 std::string。 为了构造 std::string 对象,这使得动态分配成为强制性的。

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

std::length_error::operator=

length_error& operator=( const length_error& other );
(noexcept since C++11) (C++11 起无异常抛出)

将内容赋值为 other 的内容。 如果 *thisother 都具有动态类型 std::length_error,则赋值后 std::strcmp(what(), other.what()) == 0。 复制赋值运算符不抛出任何异常。

参数

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

返回值

*this

注解

LWG issue 471 决议之后,派生的标准异常类必须具有公开可访问的复制赋值运算符。 只要 what() 获取的解释性字符串对于原始对象和复制的对象相同,就可以隐式定义它。

继承自 std::logic_error

继承自 std::exception

成员函数

[虚函数]
销毁异常对象
(std::exception 的虚公共成员函数) [编辑]
[虚函数]
返回解释性字符串
(std::exception 的虚公共成员函数) [编辑]

[编辑] 缺陷报告

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

DR 应用于 已发布行为 正确行为
LWG 254 C++98 接受 const char* 的构造函数缺失 已添加
LWG 471 C++98 std::length_error 的解释性字符串
副本是实现定义的
它们与
原始 std::length_error 对象相同

[编辑] 参见

更改存储的字符数
(std::basic_string<CharT,Traits,Allocator> 的公共成员函数) [编辑]