在他的Blog Herb Sutter写
[...] because incrementing the smart pointer reference count can usually be optimized to be the same as an ordinary increment in an optimized
shared_ptr
implementation — just an ordinary increment instruction, and no fences, in the generated code.However, the decrement must be an atomic decrement or equivalent, which generates special processor memory instructions that are more expensive in themselves, and that on top of that induce memory fence restrictions on optimizing the surrounding code.
本文是关于 shared_ptr
的实现的,我不确定他的评论是否仅适用于此或一般情况下。根据他的表述,我认为它是一般。
但是当我想到它时,我只能在 if(counter==0)
紧随其后时想到“更昂贵的递减”——这可能是 shared_ptr
。
因此我想知道 atomic 操作 ++counter
是否(通常)总是比 --counter
快>, 或者仅仅因为它被 if(--counter==0)...
与 shared_ptr
一起使用?
最佳答案
他在某处更详细地讨论了这一点,我认为在他的 atomic<> weapons 中介绍。基本上,这都是关于在 shared_ptr 用例中需要内存栅栏的地方,而不是原子增量与减量的任何内在属性。
原因是您并不真正关心使用 ref 计数的智能指针的增量的确切顺序,只要您不会错过任何内容,但是对于减量,您必须设置内存屏障,以便在触发删除的最终递减量在释放内存后,您不可能从另一个线程对智能指针拥有的对象进行先前的内存访问。
关于c++ - 原子递减比递增更昂贵吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16966043/