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?

- 6,711
- 5
- 42
- 68
-
2That is a very implementation-specific question, and as such can differ vastly between different standard libraries. But for a simple check why not use `sizeof` to check and compare to a raw pointer? – Some programmer dude Nov 07 '15 at 07:37
-
1@JoachimPileborg Because I thought other people might have the same question in future. Good point. Technically I should have asked: "Is it *possible* to implement `unique_ptr` with the same memory footprint as a raw pointer" as implementations would probably do this if possible. – Museful Nov 07 '15 at 07:41
-
the answer is here: http://stackoverflow.com/a/13460653/2183287 – fatihk Nov 07 '15 at 08:46
-
@AngelinaJolly Good link. Gonna mark this as duplicate. – Paolo M Nov 07 '15 at 08:52
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).

- 12,403
- 6
- 52
- 73