What’s so bad about a “shared reference count increment and decrement?” Two things, one related to the “shared reference count” and one related to the “increment and decrement.” Fortunately it’s not all that bad usually, which is why smart pointers are feasible for widespread use. However, it’s good to be aware of how this can incur performance costs for two reasons: one major and common, and one less likely in well-designed code (which the above, alas, is not) and so probably more minor.
First, the major reason is the performance cost of the “increment and decrement”: Because the reference count is an atomic shared variable (or equivalent), incrementing and decrementing it are internally-synchronized read-modify-write shared operations. Briefly, omitting some subtle detailed analysis, the good news is that the function entry is usually quite cheap 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.
Partager