< cpp‎ | memory
Revision as of 20:15, 17 April 2013 by Dieram3 (Talk | contribs)


Template:ddcl list begin <tr class="t-dsc-header">

Defined in header <memory>

<td></td> <td></td> <tr class="t-dcl ">

<td >
template< class Ptr > struct pointer_traits;

<td > (1) </td> <td > (since C++11) </td> </tr> <tr class="t-dcl ">

<td >
template< class T > struct pointer_traits<T*>;

<td > (2) </td> <td > (since C++11) </td> </tr> Template:ddcl list end

The pointer_traits class template provides the standardized way to access certain properties of pointer-like types. The standard template std::allocator_traits relies on pointer_traits to determine the defaults for various typedefs required by Allocator.

1) The non-specialized pointer_traits declares the following types:


Member types

Type Definition
pointer Ptr
element_type Ptr::element_type if present. Otherwise T if Ptr is a template instantiation Template<T, Args...>
difference_type Ptr::difference_type if present, otherwise std::ptrdiff_t

Member alias templates

Template Definition
template <class U> using rebind Ptr::rebind<U> if exists, otherwise Template<U, Args...> if Ptr is a template instantiation Template<T, Args...>

Member functions

obtains a dereferencable pointer to its argument
(public static member function)

2) A specialization is provided for pointer types, T*, which declares the following types

Member types

Type Definition
pointer T*
element_type T
difference_type std::ptrdiff_t

Member alias templates

Template Definition
template< class U > using rebind U*

Member functions

obtains a dereferenceable pointer to its argument}
(public static member function)


The rebind member template alias makes it possible, given a pointer-like type that points to T, to obtain the same pointer-like type that points to U. For example,

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


#include <memory>
#include <iostream>
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>
   typedef typename std::pointer_traits<Ptr>::template rebind<block> block_ptr_t;
   struct block
      std::size_t size;
      block_ptr_t next_block;
   block_ptr_t free_blocks;
int main()
    BlockList<int*> bl1;
    // The type of bl1.free_blocks is block*
    BlockList<std::shared_ptr<char>> bl2;
    // The type of bl2.free_blocks is std::shared_ptr<block>
    std::cout << bl2.free_blocks.use_count() << '\n';



See also

Template:cpp/memory/dcl list allocator traitsTemplate:cpp/memory/dcl list addressof