3

Looking in the header file for std::unique_ptr (g++ version 5.3.1) I can see that unique_ptr stores a tuple of the raw pointer it contains and the struct used to handle deletion (typically the default_deleter defined above in the same file).

template <typename _Tp, typename _Dp = default_delete<_Tp> >
class unique_ptr
{
  // use SFINAE to determine whether _Del::pointer exists
  class _Pointer        
  {
    template<typename _Up>
      static typename _Up::pointer __test(typename _Up::pointer*);
    template<typename _Up>
      static _Tp* __test(...);
    typedef typename remove_reference<_Dp>::type _Del;              
  public:
    typedef decltype(__test<_Del>(0)) type;
  };
  typedef std::tuple<typename _Pointer::type, _Dp>  __tuple_type;
  __tuple_type                                      _M_t;
// etc, etc...

I know that in C++ the size of an empty struct is nonzero, so if a unique_ptr stores a pointer (8 bytes) and an empty struct (>0 bytes), how come sizeof(std::unique_ptr<T>) is only 8 bytes?

user3288829
  • 1,266
  • 15
  • 26

0 Answers0