0

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

Idan Banani
  • 131
  • 2
  • 13

1 Answers1

3

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • which means better data locality in the latter? (sequential memory) – Idan Banani Oct 09 '18 at 08:30
  • 2
    @IdanBanani That's one thing yes. But also, memory allocations are expensive, and multiple allocations can lead to fragmented memory. – Some programmer dude Oct 09 '18 at 08:42
  • 1
    If the object and counter are allocated together, then how does shared_ptr handles the situation when the object should be destroyed but the counter shouldn't because there are weak pointers using it? – r3mus n0x Oct 09 '18 at 08:45
  • @Someprogrammerdude I think Bjarne mentioned on his keynote: "What can C++ do for embedded systems developers?" that malloc can't lead to fragmentation but the corresponding delete will. Is it true? – Idan Banani Oct 09 '18 at 08:47
  • @r3musn0x How can it happen? once the ref count equals 0 ,wouldn't both of them be deleted automatically? ( implementation of std::shared_ptr) – Idan Banani Oct 09 '18 at 08:52
  • @IdanBanani, it can happen when using weak_ptr. – r3mus n0x Oct 09 '18 at 08:55