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

后端 未结 6 774
面向向阳花
面向向阳花 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:18

    This

    shared_ptr 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.

提交回复
热议问题