shared_ptr with malloc and free

后端 未结 3 391
清歌不尽
清歌不尽 2021-01-31 04:35

I have working in large application which contain c and cpp. The all files saved as cpp extension but the code is written in c- style. I mean it is define structure rather than

3条回答
  •  不思量自难忘°
    2021-01-31 05:13

    To use a std::shared_pointer with malloc() and free() you should specify a custom deleter. This should do it

    std::shared_ptr ptr(static_cast(malloc(sizeof(T))), free);
    

    As long as you do not pass around the result of std::shared_ptr::get(), your pointer is safe.

    Edit: Added casting the result of malloc() to T*.

提交回复
热议问题