Smart Pointer Move: shared_ptr Copy vs. unique_ptr Move
Question 33 / 51 • Correct so far: 0 (0 answered)
Shared Ptr Copy
static void consumeShared(std::shared_ptr<Widget> p) {
benchmark::DoNotOptimize(p.get());
}
consumeShared(src); Unique Ptr Move
static std::unique_ptr<Widget> consumeUnique(std::unique_ptr<Widget> p) {
benchmark::DoNotOptimize(p.get());
return p;
}
ptr = consumeUnique(std::move(ptr)); Shared test data (shared-setup)
struct Widget {
int data[8];
}; Which snippet is faster?
Snippet B is faster. Copying a shared_ptr increments the atomic reference count, which requires a read-modify-write on a cache line shared across all copies. Moving a unique_ptr is a pointer swap with no atomic operation and no heap traffic.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Shared Ptr Copy | 3.94 ns | 1.0× |
| Unique Ptr Move | 0.19 ns | 21.1× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.