Unique_ptr memory size

Does the unique_ptr instance (without user deletion) have the same amount of memory as the raw pointer, or does the instance store more than just the pointer?

+8
c ++ c ++ 11 unique-ptr
source share
1 answer

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

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

produces this conclusion:

sizeof (unique_ptr) = 8

So, according to this implementation, the answer is yes .

This is not surprising: after all, unique_ptr does not add functions to raw pointers (for example, a counter like shared_ptr ). In fact, if I print sizeof(shared_ptr<int>) result this time 16 ), unique_ptr takes care of you about some aspects of pointer management.

By the way, if unique_ptr is different from the original, the generated code will be different when using one or the other. In particular, if a unique_ptr is outside the scope of your code, the compiler will generate code for the destructor of this particular specialization and will use this code every time a unique_ptr this type (and this is exactly what you want).

+7
source share

All Articles