Usage of std::shared_ptr

前端 未结 2 647
栀梦
栀梦 2021-01-06 02:45

How can I use std::shared_ptr for array of double? Additionally what are advantages/disadvantages of using shared_ptr.

相关标签:
2条回答
  • 2021-01-06 03:01

    You can also provide an array deleter:

    template class ArrayDeleter {
    public:
        void operator () (T* d) const
        { delete [] d; }
    };
    
    int main ()
    {
        std::shared_ptr array (new double [256], ArrayDeleter ());
    }
    
    0 讨论(0)
  • 2021-01-06 03:06

    It depends on what you're after. If you just want a resizable array of doubles, go with

    std::vector<double>
    

    Example:

    std::vector<double> v;
    v.push_back(23.0);
    std::cout << v[0];
    

    If sharing the ownership of said array matters to you, use e.g.

    std::shared_ptr<std::vector<double>>
    

    Example:

    std::shared_ptr<std::vector<double>> v1(new std::vector<double>);
    v1->push_back(23.0);
    std::shared_ptr<std::vector<double>> v2 = v1;
    v2->push_back(9.0);
    std::cout << (*v1)[1];
    

    Alternatively, Boost has

    boost::shared_array
    

    which serves a similar purpose. See here:

    http://www.boost.org/libs/smart_ptr/shared_array.htm

    As far as a few advantages/disadvantages of shared_ptr go:

    Pros

    • Automated shared resource deallocation based on reference counting - helps avoid memory leaks and other problems associated with things not getting deallocated when they should be
    • Can make it easier to write exception-safe code

    Cons

    • Memory overhead to store the reference count can be significant for small objects
    • Performance can be worse than for raw pointers (but measure this)
    0 讨论(0)
提交回复
热议问题