std::range_error

出自cppreference.com
< cpp‎ | error
在標頭 <stdexcept> 定義
class range_error;

定義作為異常拋出的對象類型。它能用於報告值域錯誤(即計算結果不能以目標類型表示的情形)。

會拋出此異常的標準庫組件只有 std::wstring_convert::from_bytesstd::wstring_convert::to_bytes

標準庫組件中的數學函數不會拋出此異常(數學函數按 math_errhandling 中指定報告值域錯誤)。

std::range_error 的全部成員函數均為 constexpr:在常量表達式求值中創建並使用 std::range_error 對象是可能的。

然而,std::range_error 對象通常不能為 constexpr,因為任何動態分配的存儲都必須在相同的常量表達式求值中釋放。

(C++26 起)
cpp/error/exceptioncpp/error/runtime errorstd-range error-inheritance.svg
關於這幅圖像

繼承圖

目錄

[編輯] 成員函數

(構造函數)
構造擁有給定消息的新 range_error 對象
(公開成員函數)
operator=
替換 range_error 對象
(公開成員函數)

std::range_error::range_error

range_error( const std::string& what_arg );
(1) (C++26 起為 constexpr)
range_error( const char* what_arg );
(2) (C++26 起為 constexpr)
range_error( const range_error& other );
(3) (C++11 起為 noexcept)
(C++26 起為 constexpr)
1) 構造以 what_arg 作為解釋字符串的異常對象。構造後 std::strcmp(what(), what_arg.c_str()) == 0
2) 構造以 what_arg 作為解釋字符串的異常對象。構造後 std::strcmp(what(), what_arg) == 0
3) 複製構造函數。如果 *thisother 的動態類型都是 std::range_error,那麼 std::strcmp(what(), other.what()) == 0。複製構造函數不能拋出異常。

參數

what_arg - 解釋字符串
other - 要複製的另一異常對象

異常

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

註解

因為不容許 std::range_error 的複製拋出異常,通常將此消息在內部存儲為分離分配的引用計數字符串。這也是構造函數不接收 std::string&& 參數的理由:無論如何它必須複製內容。

在解決 LWG 問題 254 之前,非複製的構造函數只接受 std::string。這導致因需要構造 std::string 對象而不得不進行動態內存分配。

在解決 LWG 問題 471 之後,派生的標準異常類必須有一個公開可訪問的複製構造函數。它可以隱式定義,只要分別在原對象和複製對象上通過 what() 獲得的兩個解釋字符串相同即可。

std::range_error::operator=

range_error& operator=( const range_error& other );
(C++11 起為 noexcept)
(C++26 起為 constexpr)

other 的內容對內容賦值。如果 *thisother 的動態類型都是 std::range_error,那麼在賦值後 std::strcmp(what(), other.what()) == 0。複製賦值運算符不能拋出異常。

參數

other - 要從其賦值的另一異常對象

返回值

*this

註解

在解決 LWG 問題 471 之後,派生的標準異常類必須有一個公開可訪問的複製賦值運算符。它可以隱式定義,只要分別在原對象和複製對象上通過 what() 獲得的兩個解釋字符串相同即可。

繼承自 std::exception

成員函數

銷毀該異常對象
(std::exception 的虛公開成員函數) [編輯]
[虛]
返回解釋性字符串
(std::exception 的虛公開成員函數) [編輯]

[編輯] 註解

功能特性測試 標準 功能特性
__cpp_lib_constexpr_exceptions 202502L (C++26) constexpr 異常類型

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 出版時的行為 正確行為
LWG 254 C++98 缺失了接受 const char* 的構造函數 已補充
LWG 471 C++98 std::range_error 的複製的解釋字符串由實現定義 它們與原 std::range_error 對象的解釋字符串相同