名稱空間
變體
操作

std::bad_weak_ptr

來自 cppreference.com
< cpp‎ | 記憶體
 
 
記憶體管理庫
(僅作說明*)
未初始化記憶體演算法
(C++17)
(C++17)
(C++17)
受約束的未初始化
記憶體演算法
C 庫

分配器
記憶體資源
垃圾回收支援
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
未初始化儲存
(直到 C++20*)
(直到 C++20*)
顯式生命週期管理
 
定義於標頭檔案 <memory>
class bad_weak_ptr;
(C++11 起)

std::bad_weak_ptr 是由 std::shared_ptr 的建構函式丟擲的異常型別,當這些建構函式接受 std::weak_ptr 作為引數,且 std::weak_ptr 指向已刪除的物件時。

cpp/error/exceptionstd-bad weak ptr-inheritance.svg

繼承圖

目錄

[編輯] 成員函式

(建構函式)
構造一個新的 bad_weak_ptr 物件
(公開成員函式)
operator=
替換 bad_weak_ptr 物件
(公開成員函式)
what
返回解釋字串
(公開成員函式)

std::bad_weak_ptr::bad_weak_ptr

bad_weak_ptr() noexcept;
(1) (C++11 起)
bad_weak_ptr( const bad_weak_ptr& other ) noexcept;
(2) (C++11 起)

構造一個新的 bad_weak_ptr 物件,帶有一個實現定義的以空字元結尾的位元組字串,該字串可透過 what() 訪問。

1) 預設建構函式。
2) 複製建構函式。如果 *thisother 都具有動態型別 std::bad_weak_ptr,則 std::strcmp(what(), other.what()) == 0

引數

其他 - 要複製的另一個異常物件

std::bad_weak_ptr::operator=

bad_weak_ptr& operator=( const bad_weak_ptr& other ) noexcept;
(C++11 起)

將內容賦值為 other 的內容。如果 *thisother 都具有動態型別 std::bad_weak_ptr,則賦值後 std::strcmp(what(), other.what()) == 0

引數

其他 - 用於賦值的另一個異常物件

返回值

*this

std::bad_weak_ptr::what

virtual const char* what() const noexcept;
(C++11 起)

返回解釋字串。

返回值

指向一個實現定義的、以空字元結尾的字串的指標,其中包含解釋性資訊。該字串適合轉換為 std::wstring 並顯示。保證該指標至少在獲取它的異常物件被銷燬之前,或直到對異常物件呼叫非 const 成員函式(例如複製賦值運算子)之前有效。

在常量求值期間,返回的字串使用普通字面量編碼進行編碼。

(C++26 起)

注意

允許但不要求實現重寫 what()

繼承自 std::exception

成員函式

銷燬異常物件
(std::exception 的虛公共成員函式) [編輯]
[virtual]
返回解釋字串
(std::exception 的虛公共成員函式) [編輯]

[編輯] 示例

#include <iostream>
#include <memory>
 
int main()
{
    std::shared_ptr<int> p1(new int(42));
    std::weak_ptr<int> wp(p1);
    p1.reset();
    try
    {
        std::shared_ptr<int> p2(wp);
    }
    catch (const std::bad_weak_ptr& e)
    {
        std::cout << e.what() << '\n';
    }
}

可能的輸出

std::bad_weak_ptr

[編輯] 缺陷報告

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

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 2376 C++11 要求對預設構造的 bad_weak_ptr 呼叫 what 返回 "bad_weak_ptr" 返回值是實現定義的

[編輯] 參見

具有共享物件所有權語義的智慧指標
(類模板) [編輯]
(C++11)
對由 std::shared_ptr 管理的物件的弱引用
(類模板) [編輯]