Can you use a shared_ptr for RAII of C-style arrays?

后端 未结 6 763
面向向阳花
面向向阳花 2020-12-13 13:48

I\'m working on a section of code that has many possible failure points which cause it to exit the function early. The libraries I\'m interacting with require that C-style

相关标签:
6条回答
  • 2020-12-13 14:11

    Some remarks for C++11 users:

    For shared_ptr, there is in C++11 a default deleter for array types defined in <memory> and standard compliant (wrt the final draft) so it can be used without additional fancy deleters for such cases:

    std::shared_ptr<char> raiiArray(new char[arrayLength], std::default_delete<char[]>()); 
    

    unique_ptr in C++11 has a partial specialization to deal with new[] and delete[]. But it does not have a shared behavior, unfortunately. Must be a good reason there is no such specialization for shared_ptr but I didn't look for it, if you know it, please share it.

    0 讨论(0)
  • 2020-12-13 14:18

    This

    shared_ptr<char*> raiiArray(new char[arrayLength]);
    

    is not a good practice, but causes undefined behaviour, as you allocate with operator new[], but shared_ptr uses operator delete to free the memory. The right thing to use is boost::shared_array or add a custom deleter.

    0 讨论(0)
  • I highly recommend simply using a std::vector. Elements in vectors are allocated on the heap, and will be deleted when the vector goes out of scope, wherever you exit the function.

    In order to pass a vector to legacy code requiring C-style arrays, simply pass &vectorName[0]. The elements are guaranteed to be contiguous in memory.

    0 讨论(0)
  • 2020-12-13 14:22

    There's boost::scoped_ptr for this.

    0 讨论(0)
  • 2020-12-13 14:26

    Use boost::scoped_array, or even better std::vector if you are dealing with an array.

    0 讨论(0)
  • 2020-12-13 14:30

    Do not use shared_ptr or scoped_ptr to hold pointers to dynamically allocated arrays. shared_ptr and scoped_ptr use delete ptr; to clean-up when the pointer is no longer referenced/goes out of scope, which invoked undefined behaviour on a dynamically allocated array. Instead, use shared_array or scoped_array, which correctly use delete[] ptr; when destructing.

    To answer your question, if you are not going to pass the smart pointer around, use scoped_array, as it has less overhead than shared_array.

    Alternatively, use std::vector as the array storage (vectors have guaranteed contiguous memory allocation).

    0 讨论(0)
提交回复
热议问题