2

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)?

intrigued_66
  • 16,082
  • 51
  • 118
  • 189
  • 5
    the point of `make_shared` is memory allocation is expensive so we should do it once – Bryan Chen May 21 '14 at 03:58
  • Ok so its not to keep the object and reference counting object close together in memory? – intrigued_66 May 21 '14 at 04:08
  • it is not the main reason – Bryan Chen May 21 '14 at 04:14
  • 1
    Down-voted for asking a decent question..... great one! So we can only ask questions we already know the answers to? ;) – intrigued_66 May 21 '14 at 04:15
  • 1
    It's not a huge difference, but it's there. [Live Example](http://coliru.stacked-crooked.com/a/0f925ffafad821e5). – Mankarse May 21 '14 at 04:19
  • 1
    Even if the data may not be in the same cache line, the pointers to the data and refcount are more likely to be in the same page when allocated together, reducing TLB caching when accessing the shared_ptr. These effects are very minor, though. – Siyuan Ren May 21 '14 at 04:50
  • 2
    Wouldn't you want them to be on different cache lines so that incrementing/decrementing the reference count doesn't unshare an unchanging object? – David Schwartz May 21 '14 at 05:17

1 Answers1

6

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.

David G
  • 94,763
  • 41
  • 167
  • 253
Filip Roséen - refp
  • 62,493
  • 20
  • 150
  • 196