C++ std::unique_ptr : Why isn't there any size fees with lambdas?

后端 未结 4 2026
暖寄归人
暖寄归人 2020-12-28 12:03

I am reading \"Effective Modern C++\". In the item related to std::unique_ptr it\'s stated that if the custom deleter is a stateless object, then no size fees o

4条回答
  •  一生所求
    2020-12-28 12:49

    From a unique_ptr implementation:

    template>
    class unique_ptr
    {
    public:
       // public interface...
    
    private:
    
      // using empty base class optimization to save space
      // making unique_ptr with default_delete the same size as pointer
    
      class _UniquePtrImpl : private deleter_type
      {
      public:
         constexpr _UniquePtrImpl() noexcept = default;
    
         // some other constructors...
    
         deleter_type& _Deleter() noexcept
         { return *this; }
    
         const deleter_type& _Deleter() const noexcept
         { return *this; }
    
         pointer& _Ptr() noexcept
         { return _MyPtr; }
    
         const pointer _Ptr() const noexcept
         { return _MyPtr; }
    
      private:
         pointer   _MyPtr;
    
      };
    
      _UniquePtrImpl   _MyImpl;
    
    };
    

    The _UniquePtrImpl class contains the pointer and derives from the deleter_type.

    If the deleter happens to be stateless, the base class can be optimized so that it takes no bytes for itself. Then the whole unique_ptr can be the same size as the contained pointer - that is: the same size as an ordinary pointer.

提交回复
热议问题