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
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.