Search code examples
c++operator-overloadingnew-operatorsmart-pointers

Why does `make_unique` use `new` while make_shared use `::new`


I am working on a project where a couple of the classes overload operator new and delete to utilize free-lists and I tried to use make_shared to have my allocations managed by smart pointers when I realized that make_shared does not use the overloaded versions but makes an explicit call the global ::new. But according to this make_unique does use the overloaded versions. Which is quite baffling to me. Why does make_shared choose to ignore operator overloading but make_unique doesn't?


Solution

  • make_shared has to allocate two things: the object being constructed and the shared_ptr's control block. To improve performance, it allocates one chunk of memory big enough for both and then placement-news them.

    make_unique doesn't need to do that since a unique_ptr doesn't need a control block.


    If you want to control how memory is allocated for an object to be managed by a shared_ptr, create an appropriate allocator class and use allocate_shared instead of make_shared.