名稱空間
變體
操作

std::pointer_traits

來自 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*)
顯式生命週期管理
 
std::pointer_traits
成員函式
 
定義於標頭檔案 <memory>
template< class Ptr >
struct pointer_traits;
(1) (C++11 起)
template< class T >
struct pointer_traits<T*>;
(2) (C++11 起)

pointer_traits 類模板提供了一種標準化的方式來訪問類似指標型別(花式指標,例如 boost::interprocess::offset_ptr)的某些屬性。std::allocator_traits 標準模板依賴於 pointer_traits 來確定 Allocator 所需的各種 typedef 的預設值。

1) 非特化的 pointer_traits 有條件地宣告以下成員

/*element-type-of*/<Ptr>

  • Ptr::element_type 如果存在;
  • 否則,如果 Ptr 是類模板特化 Template<T, Args...>,其中 Args... 是零個或多個型別引數,則為 T
  • 否則,未定義。

如果 /*element-type-of*/<Ptr> 未定義,則主模板沒有本頁面中指定的成員。

目錄

[編輯] 成員型別

型別 定義
pointer Ptr
element_type /*element-type-of*/<Ptr>
difference_type Ptr::difference_type 如果存在,否則 std::ptrdiff_t

[編輯] 成員別名模板

Template 定義
template< class U > using rebind 如果存在 Ptr::rebind<U>,則為其,否則如果 Ptr 是模板特化 Template<T, Args...>,則為 Template<U, Args...>

[編輯] 成員函式

[靜態]
獲取指向其引數的可解引用指標
(公共靜態成員函式) [編輯]
2) 為指標型別 T* 提供了特化,它宣告以下成員

[編輯] 成員型別

型別 定義
pointer T*
element_type T
difference_type std::ptrdiff_t

[編輯] 成員別名模板

Template 定義
template< class U > using rebind U*

[編輯] 成員函式

[靜態]
獲取指向其引數的可解引用指標
(公共靜態成員函式) [編輯]

[編輯] 程式定義特化的可選成員函式

[靜態] (C++20)(可選)
從花式指標獲取原始指標(pointer_to 的逆操作)
(公共靜態成員函式) [編輯]

[編輯] 注意

rebind 成員模板別名使得給定指向 T 的類似指標型別,可以獲取指向 U 的相同類似指標型別。例如,

using another_pointer = std::pointer_traits<std::shared_ptr<int>>::rebind<double>;
static_assert(std::is_same<another_pointer, std::shared_ptr<double>>::value);

使用者定義的花式指標型別的特化可以提供一個額外的靜態成員函式 to_address 來定製 std::to_address 的行為。

(C++20 起)
特性測試 標準 特性
__cpp_lib_constexpr_memory 201811L (C++20) std::pointer_traits 中的 constexpr

[編輯] 示例

#include <iostream>
#include <memory>
 
template<class Ptr>
struct BlockList
{
    // Predefine a memory block
    struct block;
 
    // Define a pointer to a memory block from the kind of pointer Ptr s
    // If Ptr is any kind of T*, block_ptr_t is block*
    // If Ptr is smart_ptr<T>, block_ptr_t is smart_ptr<block>
    using block_ptr_t = typename std::pointer_traits<Ptr>::template rebind<block>;
 
    struct block
    {
        std::size_t size{};
        block_ptr_t next_block{};
    };
 
    block_ptr_t free_blocks;
};
 
int main()
{
    [[maybe_unused]]
    BlockList<int*> bl1;
    // The type of bl1.free_blocks is BlockList<int*>:: block*
 
    BlockList<std::shared_ptr<char>> bl2;
    // The type of bl2.free_blocks is
    // std::shared_ptr<BlockList<std::shared_ptr<char>>::block>
    std::cout << bl2.free_blocks.use_count() << '\n';
}

輸出

​0​

[編輯] 缺陷報告

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

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 3545 C++11 element_type 無效時,主模板導致硬錯誤 變為 SFINAE 友好

[編輯] 另請參閱

提供關於分配器型別的資訊
(類模板) [編輯]
(C++11)
獲取物件的實際地址,即使 & 運算子被過載
(函式模板) [編輯]