If the size of an empty class can't be 0, what magic is doing std::tuple so the sizeof of unique_ptr is returning 8 in a 64 bit machine?
In unique_ptr the member is defined as:
typedef std::tuple<typename _Pointer::type, _Dp> __tuple_type; __tuple_type _M_t;
Where _Dp is the deleter class.
Compiler is gcc version 4.7.1 (Debian 4.7.1-7)
This means that unique_ptr is exactly the same size as that pointer, either four bytes or eight bytes.
std::unique_ptr::unique_ptrThe object is empty (owns nothing), with value-initialized stored pointer and stored deleter. construct from pointer (3) The object takes ownership of p, initializing its stored pointer to p and value-initializing its stored deleter.
A std::unique_ptr owns of the object it points to and no other smart pointers can point to it. When the std::unique_ptr goes out of scope, the object is deleted. This is useful when you are working with a temporary, dynamically-allocated resource that can get destroyed once out of scope.
std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.
The reason is that the typename _Dp = default_delete<_Tp>
is an empty class and the tuple
template employs empty base class optimization.
If you instantiate the unique_ptr
with a non-default delete, you should see the size increase.
unique_ptr
as specified can have zero overhead because the only thing needed to implement it is to modify the process of copying/moving a raw pointer; no additional information is necessary. Therefore unique_ptr
doesn't need to store anything besides the pointer and can be the same size as a pointer.
As to how your particular implementation, achieves that; Only most derived types need to have a size greater than zero. Empty base classes can take up zero bytes. It's quite common for standard library implementations to take advantage of the so-called 'empty base class' optimization for all kinds of things, from stateless allocators in containers to tuple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With