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?
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.
This means that unique_ptr is exactly the same size as that pointer, either four bytes or eight bytes.
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.
std::unique_ptr::unique_ptr default constructor (1), and (2) The object is empty (owns nothing), with value-initialized stored pointer and stored deleter.
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).
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