C++ Smart Pointer performance

前端 未结 6 1710
北荒
北荒 2021-02-07 05:24

How much do using smart pointers, particularly boost::shared_ptr cost more compared to bare pointers in terms of time and memory? Is using bare pointers better for performance i

6条回答
  •  别那么骄傲
    2021-02-07 05:58

    Dereferencing smart pointers is typically trivial, certainly for boost in release mode. All boost checks are at compile-time. (Smart pointers could in theory do smart stuff across threads). This still leaves a lot of other operations. Nicola mentioned construction, copying and destruction. This is not the complete set, though. Other important operations are swapping, assignment and resetting to NULL. Basically, any operation that requires smartness.

    Note that some of these operations are excluded by some smart pointers. E.g. boost::scoped_ptr cannot even be copied, let alone be assigned. As this leaves less operations, the implementation can be optimized for these fewer methods.

    In fact, with TR1 coming up, it's quite likely that compilers can do better with smart pointers than raw pointers. E.g. it's possible that a compiler can prove that a smart non-copyable pointer is not aliased in some situations, merely because it's non-copyable. Think about it: aliasing occurs when two pointers are created pointing to the same object. If the first pointer cannot be copied, how would a second pointer end up pointing to the same object? (There are ways around that, too - operator* has to return an lvalue)

提交回复
热议问题