使用shared_ptr的开销和实现 [英] Overhead and implementation of using shared_ptr
问题描述
简介:我正在处理多线程代码,我必须在两个线程之间共享动态分配的对象。为了使我的代码更清洁(更少容易出错),我想明确删除每个线程中的对象,这就是为什么我想使用 shared_ptr
。
第一个问题:
我想知道 - > ;在运行时,
有一些额外的开销(例如大于 shared_ptr
中的运算符 unique_ptr
)。对象我在说的通常是longlife实例只复制一次后创建(当我在线程之间分配),然后我只访问这些对象的方法和字段。
I
第二个问题: p>在libstdc ++中优化的 shared_ptr
有多好?它总是使用互斥或利用原子操作(我专注于x86和ARM平台)?
第一个问题:使用
operator->
$ b b
我看到的所有实现在 shared_ptr< T>
中有一个本地缓存 T * 类,使得字段在堆栈上,因此
operator->
具有与使用堆栈local T * $ c $
我希望libstdc ++在x86平台上使用原子,无论是通过标准设施还是特定的g ++内在函数(在旧版本中)。我相信Boost的实现已经这样做了。
但是,我不能评论ARM。
>注意:C ++ 11引入移动语义,许多副本在使用 shared_ptr
时自然避免。
注意:请阅读 shared_ptr
此处,您可以使用对 shared_ptr
( const
)的引用),以避免大多数副本/销毁一般,所以这些的性能不太重要。
Short introduction: I am working on multithread code and I have to share dynamically allocated objects between two threads. To make my code cleaner (and less error-prone) I want to explicitly "delete" objects in each thread and that's why I want to use shared_ptr
.
First question:
I want to know if implementation of -> operator
in shared_ptr
has some extra overhead (e.g. larger then unique_ptr
) during run time. Objects I am talking about are usually longlife instances copied only once after creation (when i distribute them between threads), then I only access these objects' methods and fields.
I am aware, that shared_ptr
only protect reference counting.
Second question:
How well are shared_ptr
optimized in libstdc++? Does it always use mutex or take advantage of atomic operations (I focus on x86 and ARM platforms)?
First question: using
operator->
All the implementations I have seen have a local cache of T*
right in the shared_ptr<T>
class so that the field is on the stack, operator->
has thus a comparable cost to using a stack local T*
: no overhead at all.
Second question: mutex/atomics
I expect libstdc++ to use atomics on x86 platform, whether through standard facilities or specific g++ intrinsics (in the older versions). I believe the Boost implementation already did so.
I cannot, however, comment on ARM.
Note: C++11 introducing move semantics, many copies are naturally avoided in the usage of shared_ptr
.
Note: read about correct usage of shared_ptr
here, you can use references to shared_ptr
(const
or not) to avoid most of the copies/destruction in general, so the performance of those is not too important.
这篇关于使用shared_ptr的开销和实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!