Search code examples
c++11shared-ptrsmart-pointersmake-shared

make_shared() reference counting in C++


From: A Tour of C++ (Second edition)

13.2.1 unique_ptr and shared_ptr

Using make_shared() is not just more convenient than separately making an object using new and then passing it to a shared_ptr, it is also notably more efficient because it does not need a separate allocation for the use count that is essential in the implementation of a shared_ptr.

My question: How come shared_ptr does need to allocate memory for reference counting and make_shared() not? (Will it allocate it only once there are at least two references to the data?)

Edit: I haven't noticed the word "seperate" in the text, so my question is irrelevant ,Tough - I would still like to ask why make_shared() is more efficient


Solution

  • A shared pointer contains two parts: The pointer to the "object" you have created, and a pointer to a special control block that contains the reference counter and possibly some other meta-data needed.

    If you create your own std::shared_ptr object, these two memory block will be allocated separately. If you use std::make_shared then the function will only make a single allocation for both blocks of memory.