Hacker News new | ask | show | jobs
by mathias_10gen 5359 days ago
Actually since most if not all CPUs have an atomic increment instruction it is quite easy to make shared_ptr<> thread-safe. In fact, that is what boost::shared_ptr<> does. This makes it a good tool for resources that may be shared between threads or for cases where it's just not worth the mental overhead of worrying about ownership.

That said, shared_ptr isn't a solution to everything. Sometimes scoped_ptr (called unique_ptr in tr1) or intrusive_ptr is a better tool. Often if you don't want to share or transfer ownership, passing around a raw ptr or reference is even better and the only option if you want to work with embedded structs (but the newed memory should still be owned by some RAII smart pointer even if it gets passed around as a bare pointer)

1 comments

While there are atomic instructions, they usually require memory barriers to ensure modern CPUs order the instructions properly to get the desired behavior. This can have a negative effect on overall performance if these atomic ops are hit in hot spot.