Does Boost, or anything else, contain a container will act like a shared pointer but allow me to control what happens to the shared ‘resource’ at the end of it’s life? I want to encapsulate an object that can be handed around but, when no longer needed can be closed in a context defined way.
For example, I might want to create and pass around a file handle knowing that when it goes out of scope, the file will be closed automatically, but I don’t want to delete the handle.
I could implement it myself, but would rather not get into that if the framework already exists – someone has no doubt done it better. I can’t use boost::shared_ptr, at least not in it’s normal form, as the resource should not be deleted at end of life.
Are you aware that
std::shared_ptrcan take a custom deleter class? This need not actually use “delete” or “free”, but could easily use some other sort of mechanism (such as a reference counting mechanism’sreleaseand so on).Here’s a dead simple example for you:
The deleter just needs to be a function that takes the pointer type that the
shared_ptrwraps. In this case, whenfoo goes out of scope,shared_ptrwill close the file for you. (Note: this isn’t a totally sensible implementation, because no error values are checked. It is just an example).