有通过存储控制对象内的引用计数,以增加的shared_ptr的效率的方法吗? [英] Is there a way to increase the efficiency of shared_ptr by storing the reference count inside the controlled object?
问题描述
这是在我的code成为一个共同的模式,因为当我需要管理,需要将不可复制,因为无论答是重或B.它是一个操作系统资源,如一个对象一个关键的部分:
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 system resource, such as a critical section:
class Resource;
class Implementation : public boost::noncopyable
{
friend class Resource;
HANDLE someData;
Implementation(HANDLE input) : someData(input) {};
void SomeMethodThatActsOnHandle() {
//Do stuff
};
public:
~Implementation() { FreeHandle(someData) };
};
class Resource
{
boost::shared_ptr<Implementation> impl;
public:
Resource(int argA) explicit {
HANDLE handle =
SomeLegacyCApiThatMakesSomething(argA);
if (handle == INVALID_HANDLE_VALUE)
throw SomeTypeOfException();
impl.reset(new Implementation(handle));
};
void SomeMethodThatActsOnTheResource() {
impl->SomeMethodThatActsOnTheHandle();
};
};
这样,shared_ptr的需要照顾的引用计数头痛,让资源
来可拷贝,即使底层手柄只能关闭一次对它的所有引用被销毁
This way, shared_ptr takes care of the reference counting headaches, allowing Resource
to be copyable, even though the underlying handle should only be closed once all references to it are destroyed.
不过,这似乎是我们可以节省分配的shared_ptr的引用计数,这样分开,如果我们能不知何故移动实施内部的数据,例如升压转换器的介入式容器做的开销。
However, it seems like we could save the overhead of allocating shared_ptr's reference counts and such separately if we could move that data inside Implementation
somehow, like boost's intrusive containers do.
如果这个正在唠叨一些人的premature优化梳理,其实我同意,我不需要这个对我目前的项目。不过我很好奇,如果这是可能的。
If this is making the premature optimization hackles nag some people, I actually agree that I don't need this for my current project. But I'm curious if it is possible.
推荐答案
一个部分的解决方案是使用 make_shared
以创建你的的shared_ptr
秒。例如,
A partial solution is to use make_shared
to create your shared_ptr
s. For example,
auto my_thing = std::make_shared<Thing>();
而不是
auto my_thing = std::shared_ptr<Thing>(new Thing);
这还是非侵入式的,所以没什么需要改变。 make_shared
的好的实现结合内存分配的引用计数和对象本身。这节省内存分配,并保持靠近对象为更好局部性的计数。这是不是很类似升压高效:intrusive_ptr
,但它是值得考虑的。
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.
这篇关于有通过存储控制对象内的引用计数,以增加的shared_ptr的效率的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!