Should I switch from using boost::shared_ptr to std::shared_ptr?

后端 未结 8 1767
一生所求
一生所求 2020-12-23 02:06

I would like to enable support for C++0x in GCC with -std=c++0x. I don\'t absolutely necessarily need any of the currently supported C++11 features in GCC 4.5 (

相关标签:
8条回答
  • 2020-12-23 03:00

    Aside from implementation consistency, boost::shared_ptr currently retains at least two niche advantages over std::shared_ptr:

    • The availability of boost::make_shared_noinit. It's particularly useful in conjunction with arrays, avoiding both the cost of zero-initialization and the overhead of separate allocation. (FWIW, it's also a proposed addition to the standard.)
    • Boost.Python makes special use of boost::shared_ptr's support for type-erased custom deleters, but doesn't yet do the same for std::shared_ptr.
    0 讨论(0)
  • 2020-12-23 03:04

    There are a couple of reasons to switch over to std::shared_ptr:

    • You remove a dependency on Boost.
    • Debuggers. Depending on your compiler and debugger, the debugger may be "smart" about std::shared_ptr and show the pointed to object directly, where it wouldn't for say, boost's implementation. At least in Visual Studio, std::shared_ptr looks like a plain pointer in the debugger, while boost::shared_ptr exposes a bunch of boost's innards.
    • Other new features defined in your linked question.
    • You get an implementation which is almost guaranteed to be move-semantics enabled, which might save a few refcount modifications. (Theoretically -- I've not tested this myself) As of 2014-07-22 at least, boost::shared_ptr understands move semantics.
    • std::shared_ptr correctly uses delete [] on array types, while boost::shared_ptr causes undefined behavior in such cases (you must use shared_array or a custom deleter) (Actually I stand corrected. See this -- the specialization for this is for unique_ptr only, not shared_ptr.)

    And one major glaring reason not to:

    • You'd be limiting yourself to C++11 compiler and standard library implementations.

    Finally, you don't really have to choose. (And if you're targeting a specific compiler series (e.g. MSVC and GCC), you could easily extend this to use std::tr1::shared_ptr when available. Unfortunately there doesn't seem to be a standard way to detect TR1 support)

    #if __cplusplus > 199711L
    #include <memory>
    namespace MyProject
    {
        using std::shared_ptr;
    }
    #else
    #include <boost/shared_ptr.hpp>
    namespace MyProject
    {
        using boost::shared_ptr;
    }
    #endif
    
    0 讨论(0)
提交回复
热议问题