Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory footprint of unique_ptr [duplicate]

Does a unique_ptr instance (without a custom deleter) have the same memory footprint as a raw pointer or does an instance store more than just the pointer?

like image 726
Museful Avatar asked Nov 07 '15 07:11

Museful


People also ask

What happens when you copy a unique_ptr?

A unique_ptr does not share its pointer. It cannot be copied to another unique_ptr , passed by value to a function, or used in any C++ Standard Library algorithm that requires copies to be made. A unique_ptr can only be moved.

How big is unique_ptr?

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

Why would you choose Shared_ptr instead of unique_ptr?

Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. A shared_ptr is a container for raw pointers.

What is the default value of unique_ptr?

std::unique_ptr::unique_ptr default constructor (1), and (2) The object is empty (owns nothing), with value-initialized stored pointer and stored deleter.


1 Answers

As @JoachimPileborg suggested, with GCC 4.8 (x64) this code

std::cout << "sizeof(unique_ptr) = " << sizeof(std::unique_ptr<int>) << '\n';

produces this output:

sizeof(unique_ptr) = 8

So, under this implementation, the answer is yes.

This is not astonishing: after all, unique_ptr doesn't add features to raw pointers ( e.g. a counter as shared_ptr does. In fact, if I print sizeof(shared_ptr<int>) the result this time is 16). unique_ptr takes care for you about of some aspects of pointers management.

By the way, being a unique_ptr different from a raw one, the generated code will be different when using one or another. In particular, if a unique_ptr goes out of scope in your code, the compiler will generate code for the destructor of that particular specialization and it will use that code every time a unique_ptr of that type will be destroyed (and that is exactly what you want).

like image 166
Paolo M Avatar answered Oct 04 '22 10:10

Paolo M