Is there a way to increase the efficiency of shared_ptr by storing the reference count inside the controlled object?

前端 未结 4 1929
有刺的猬
有刺的猬 2021-01-20 19:15

This is becoming a common pattern in my code, for when I need to manage an object that needs to be noncopyable because either A. it is \"heavy\" or B. it is an operating sys

4条回答
  •  囚心锁ツ
    2021-01-20 19:44

    A partial solution is to use make_shared to create your shared_ptrs. For example,

    auto my_thing = std::make_shared();
    

    instead of

    auto my_thing = std::shared_ptr(new Thing);
    

    It's still non-intrusive, so nothing else needs to change. Good implementations of make_shared combine the memory allocation for the reference count and the object itself. That saves a memory allocation and keeps the count close to the object for better locality. It's not quite as efficient as something like boost:intrusive_ptr, but it's worth considering.

提交回复
热议问题