Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can std::unique_ptr have no size overhead?

Tags:

c++

c++11

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)

like image 836
piotr Avatar asked Nov 19 '12 19:11

piotr


People also ask

How big is a unique_ptr?

This means that unique_ptr is exactly the same size as that pointer, either four bytes or eight bytes.

Is unique_ptr empty?

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.

What happens when unique_ptr goes out of scope?

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.

What is the use of std :: unique_ptr?

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.


2 Answers

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.

like image 50
chill Avatar answered Sep 19 '22 23:09

chill


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.

like image 23
bames53 Avatar answered Sep 20 '22 23:09

bames53