Search code examples
c++c++11memory-managementshared-ptrmake-shared

Using make_shared with shared_ptr<T>s only beneficial for T < 56 bytes?


As I understand it if you use std::make_shared it creates the reference counting object at the same time as the underlying object.

However, if the object pointer to by the smart_ptr is greater than 56 bytes wouldn't the reference counter end up being located in a different cache line anyway (because cache lines are 64 bytes)?


Solution

  • Note: The cache-line is not the same size on every platform, nor is the size of a pointer always the same.. be careful about making assumptions based on the numbers in the question.


    Why std::make_shared?

    std::make_shared exists for three (main) reasons;

    • Means to allocate memory for both the ref-counter, and the object being tracked at once (generally memory allocations are expensive);
    • an exception-safe way to construct and initialize a std::shared_ptr;
    • and code brevity.

    What about the cache-line and std::make_shared?

    Honestly this is beyond the scope and purpose of std::make_shared. The C++ Standard has no idea of what a "cache-line" is, and the design described in the standard is written in such matter that it's not targetting any specific platform.

    Even if there will be *cache-misse*s because the ref-counter and the object can't fit inside the same cache-line, we still have all the benefits previously listed, and std::make_shared still does the job it's intended to solve.

    Note: One could say that "keeping the ref-counter and the object close together in memory" is just a sweet little bonus.