C++ 命名要求: NullablePointer (C++11 起)
指定該型別是一個類指標物件,可以與 std::nullptr_t 物件進行比較。
目錄 |
[編輯] 要求
該型別必須滿足以下所有要求
- EqualityComparable(可相等比較)
- DefaultConstructible(可預設構造)
- CopyConstructible(可複製構造)
- CopyAssignable(可複製賦值)
- Swappable(可交換)
- Destructible(可析構)
此外,經過值初始化的該型別物件必須產生一個該型別的空值。此空值只能與自身相等。該型別的預設初始化可能會產生不確定或錯誤(C++26 起)的值。
該型別的值必須能夠上下文隱式轉換為 bool。此轉換的效果是,如果該值等同於其空值,則返回 false,否則返回 true。
此型別執行的任何操作都不得丟擲異常。
給定該型別的兩個值 p 和 q,以及 np 是 std::nullptr_t 型別的值(可能帶有 const 限定符),該型別必須滿足以下附加表示式:
宣告 | 效果 | ||||
Type p(np);
Type p = np; |
之後,p 等同於 nullptr | ||||
表示式 | 效果 | ||||
Type(np) | 一個等同於 nullptr 的臨時物件 | ||||
p = np | 必須返回一個 Type& ,之後,p 等同於 nullptr | ||||
p != q |
效果為 !(p == q) | ||||
p == np
np == p |
效果為 (p == Type()) | ||||
p != np
np != p |
效果為 !(p == np) |
[編輯] 注意
請注意,對於 NullablePointer 型別,並不要求解引用(operator* 或 operator->)。一個滿足這些要求的最小型別是
class handle { int id = 0; public: handle() = default; handle(std::nullptr_t) {} explicit operator bool() const { return id != 0; } friend bool operator==(handle l, handle r) { return l.id == r.id; } friend bool operator!=(handle l, handle r) { return !(l == r); } // or only a defaulted operator== (since C++20) };
[編輯] 標準庫
以下型別滿足 NullablePointer
為了與標準庫元件通訊,以下型別必須滿足 NullablePointer
- 每個 Allocator 型別
X
的成員型別X::pointer
、X::const_pointer
、X::void_pointer
和X::const_void_pointer
。 - std::unique_ptr 的成員型別
pointer
。
|
(C++23 起) |
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 2114 (P2167R3) |
C++11 | 上下文可轉換為 bool 的要求太弱,未能反映實現者的預期 | 要求已加強 |