I have a smart pointer for an object, that I need to pass to a method, that only accepts a pointer pointer.
Here's an example, where the original smart pointer loses the ownership.
int main(int argc, char* argv[])
{
std::unique_pointer<pcap_if_t> object;
auto object_pointer = object.get();
pcap_findalldevs(&object_pointer, ...); // The unique_ptr loses ownership after being passed to the function
}
How would I accomplish this, without the original smart pointer losing the pointer ownership?
EDIT:
The function I'm calling is pcap_findalldevs in libpcap. I'm afraid that the function might be the cause of losing ownership.
I have updated my code example to reflect the what I actually do.
Suppose you have a shared_ptr variable named ptr . You can get the reference either by using *ptr or *ptr. get() . These two should be equivalent, but the first would be preferred.
A smart pointer is like a regular (typed) pointer, like "char*", except when the pointer itself goes out of scope then what it points to is deleted as well. You can use it like you would a regular pointer, by using "->", but not if you need an actual pointer to the data. For that, you can use "&*ptr".
std::shared_ptr::getReturns the stored pointer. The stored pointer points to the object the shared_ptr object dereferences to, which is generally the same as its owned pointer.
A Smart Pointer is a wrapper class over a pointer with an operator like * and -> overloaded. The objects of the smart pointer class look like normal pointers. But, unlike Normal Pointers it can deallocate and free destroyed object memory.
Function which takes pointer to pointer usually does so because it might change it, and pcap_findalldevs
is indeed does that. And that pointer should be released with call to pcap_freealldevs
.
So your best bet is unique_ptr
with custom deleter aquiring ownership from raw pointer:
struct pcap_deleter
{
void operator()(pcap_if_t* ptr)
{
pcap_freealldevs(ptr);
}
};
//...
using pcap_ptr = std::unique_ptr<pcap_if_t, pcap_deleter>
pcap_ptr get_devs() {
pcap_if_t* object_pointer;
pcap_findalldevs(&object_pointer, ...);
return pcap_ptr(object_pointer);
}
//...
auto object = get_devs();
Here's an example, where the original smart pointer loses the ownership.
Nope. The unique_ptr retains ownership after a call to get()
unique_ptr will lose ownership after a call to release()
reference: http://en.cppreference.com/w/cpp/memory/unique_ptr
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With