shared_ptr with malloc and free

后端 未结 3 404
清歌不尽
清歌不尽 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:14

    Can I use shared_ptr with malloc and free.

    Yes.

    Can anyone point out me sample code base.

    You need to provide a custom deleter, so that memory is released using free rather than the default delete. This can be a pointer to the free function itself:

    shared_ptr memory(malloc(1024), free);
    

    Remember that malloc and free only deal with raw memory, and you're responsible for correctly creating and destroying any non-trivial objects you might want to keep in that memory.

    if I create shared_ptr in my application and pass this pointer to another function if they are using malloc or calloc. will it impact any functionality.

    I don't quite follow the question. You can use this shared_ptr interchangably with "normal" shared pointers, if that's what you're asking. Type erasure ensures that users of the pointers aren't affected by different types of deleter. As with any shared pointer, you have to be a bit careful if you extract the raw pointer with get(); specifically, don't do anything that might free it, since you've irrevocably assigned ownership to the shared pointer.

    We have call some function which accept double pointer and fill the structure inside their application and use malloc Can we assign those pointer to shared_ptr.

    I guess you mean something like:

    double * make_stuff() {
       double * stuff = static_cast(malloc(whatever));
       put_stuff_in(stuff);
       return stuff;
    }
    
    shared_ptr shared_stuff(make_stuff(), free);
    

    UPDATE: I didn't spot the phrase "double pointer", by which I assume you mean the C-style use of a pointer to emulate a reference to emulate a return value; you can do that too:

    void make_stuff(double ** stuff);
    
    double * stuff = 0;
    make_stuff(&stuff);
    shared_ptr shared_stuff(stuff, free);
    

    How will handle with realloc and calloc

    It's fine to initialise the shared pointer with the result of calloc, or anything else that returns memory to be released using free. You can't use realloc, since shared_ptr has taken ownership of the original pointer and won't release it without calling free.

提交回复
热议问题