Reputation: 10477
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.
Upvotes: 3
Views: 744
Reputation: 4025
Since you can't use Boost or the std::shared_ptr, you could write a smart pointer be it shared or unique that has custom Deleter.
Upvotes: 1
Reputation: 6145
Are you aware that std::shared_ptr
can 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's release
and so on).
Here's a dead simple example for you:
std::shared_ptr<FILE> foo(fopen("la", "r"), fclose);
The deleter just needs to be a function that takes the pointer type that the shared_ptr
wraps. In this case, whenfoo goes out of scope, shared_ptr
will close the file for you. (Note: this isn't a totally sensible implementation, because no error values are checked. It is just an example).
Upvotes: 8
Reputation: 17428
If you are using a compiler that supports the C++11 std::shared_ptr
, one of the constructors takes a custom "deleter" function. This would allow you to write your own function for "releasing" the resources.
EDIT - I forgot that std::shared_ptr was actually in the TR1 update to C++, so if your compiler supports TR1 you should be in good shape.
Upvotes: 3