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

后端 未结 6 766
面向向阳花
面向向阳花 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 and standard compliant (wrt the final draft) so it can be used without additional fancy deleters for such cases:

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

    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.

提交回复
热议问题