Let's say I have an underlying buffer
char *c = new char[100];
which I reference through a View object (which does not take ownership, but offers the actual functionality)
View *v = new View(c);
Now I would like to construct a smart pointer, such that when dereferenced gives the View* v
object, but when destroyed destroys both the View* v
and char* c
objects. Something like:
std::unique_ptr<View, my_deleter> p(v,my_deleter(c));
such that *p
gives *v
instance but when deleted my_deleter
actually destroys both v
and c
.
In case you want to see an actual use case for this functionality, consider a function get_image()
obtaining an image from a hardware camera, which must return an Eigen object for further processing. Eigen::Map
is a suitable object (which acts as a View object) because no copy of the underlying driver buffer is needed. Nevertheless I must also return a reference to the original buffer object, because it must eventually be destroyed. This forces the receiving party to ensure deallocation eventually happens, at code that may know nothing about the camera implementation and its buffer objects. Returning a smart pointer to Eigen::Map
which eventually deallocates the buffer object is desirable.
CodePudding user response:
Here's an example of how to do it:
#include <iostream>
#include <memory>
struct A
{
~A() { std::cout << "~A()" << std::endl; }
};
struct B
{
~B() { std::cout << "~B()" << std::endl; }
};
int main() {
A* pa = new A();
auto deleter = [pa](B* pb) { delete pa; delete pb; };
std::unique_ptr<B, decltype(deleter)> pb(new B(), deleter);
}