简体   繁体   中英

How to replace char* using smart pointers?

I have to expose an API which takes a char* as input argument. The char* points to a chunk of binary data on heap. In this case the caller have to manage the memory allocation and deletion.

Is there a way that I could use a shared_ptr as input argument instead of a raw pointer.

void func(char* data)
{
   //some operation
}

If func simply observes the data without changing it, have it accept a const char * . The caller can store the pointer in any smart pointer, and use the get() function to get a bare pointer to pass to func .

If func changes the data, I like to steal ideas from Rust and pass in a std::unique_ptr and return a std::unique_ptr . The caller passes away ownership and then receives back ownership of a pointer, but possibly a completely different pointer. And it doesn't matter.

If func has to modify the data and it has to accept a char * then just use get() as before from any smart pointer that you want. As long as func does not store the pointer somewhere nothing will break.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM