Using shared_ptr
on C-style resources
With boost::shared_ptr
, you can pass a function pointer to a "deleter" that will be called automatically when the reference count reaches zero. This feature allows shared_ptr to be used to manage resources returned by legacy C APIs.
Consider leaving your legacy my_src_create
intact, and provide a new "factory" function that returns a shared_ptr
:
void my_src_deleter(my_src_type* raw_ptr)
{
my_src_destroy(raw_ptr);
}
typedef boost::shared_ptr<my_src_type> my_src_shared_ptr;
my_src_shared_ptr create_my_src(...)
{
my_src_type* raw_ptr;
my_src_create(&raw_ptr, ctx, topic, handle_src_event, NULL, NULL);
return my_src_shared_ptr(raw_ptr, &my_src_deleter);
}
std::map<string, my_src_shared_ptr> dict;
BOOST_FOREACH(std::string topic, all_topics)
{
dict[topic] = create_my_src(ctx, topic, handle_src_event, NULL, NULL);
}
Wrapping Legacy C Struct/Functions in a Class
Alternatively, (as jpalecek suggested) you can wrap my_src
in a class. Creation and destruction of legacy my_src
objects is handled in the constructor and destructor. If you're going to do this, you should think about whether or not you want your MySrc
class to be copyable. If MySrc
is heavyweight or expensive to create, you'll probably want to make it non-copyable and consider using shared_ptr<MySrc>
if there is going to be shared ownership of MySrc
:
class MySrc
{
public:
typedef boost::shared_ptr<MySrc> Ptr;
MySrc(...) { my_src_create(&src_, ...); }
~MySrc() { my_src_destroy(&src_); }
// Other member functions that uses my_src legacy functions
private:
my_src_type* src_;
// Make copy-constructor and assignment private to disallow copies
MySrc(const MySrc& rhs) {}
MySrc& operator=(const MySrc& rhs) {return *this;}
};
std::map<string, MySrc::Ptr> dict;
BOOST_FOREACH(std::string topic, all_topics)
{
dict[topic] = MySrc::Ptr(
new MySrc(ctx, topic, handle_src_event, NULL, NULL) );
}
Note that you can also use the MySrc
class to wrap legacy functions that operate on my_src instances.
If you want MySrc
to be copyable, then make sure to implement the copy-constructor and assignment operator so that a deep-copy is performed.