How to get the pointer to a shared_ptr?

boost, c++, shared-ptr

Solution

No.

Basically, you have to do it the old C way and then convert the result to a `shared_pointer` somehow.

You can do it by simply initializing the shared_pointer

my_src_type* pSrc;
my_src_create(&src, ctx, topic, handle_src_event, NULL, NULL);
shared_ptr<my_src_type> sp(pSrc);

but beware, this will fail if the `my_src_create` function can return an already existing object. Also, if there is a `my_src_destroy` function, it won't be called.

IMHO the cleanest way is to wrap your structure in a C++ class:

class MySrc {
  my_src_type* pSrc;
public:
  MySrc(...) { my_src_create(&pSrc, ...); }
  ~MySrc() { my_src_destroy(&pSrc); }
private:
  MySrc(const MySrc&);
  void operator=(const MySrc&); // disallow copying
};

and then use shared pointer for `MySrc` the ususal way.

Problem

I am now hacking an old C code, try to make it more C++/Boost style: there is a resource allocation function looks like: ``` my_src_type* src; my_src_create(&src, ctx, topic, handle_src_event, NULL, NULL); ``` i try to wrap src by a shared_ptr: ``` shared_ptr<my_src_type> pSrc; ``` I forgot to mention just now. I need to do this as a loop ``` std::map<string, shared_ptr<my_src_type> > dict; my_src_type* raw_ptr; BOOST_FOREACH(std::string topic, all_topics) { my_src_create(&raw_ptr, ctx, topic, handle_src_event, NULL, NULL); boost::shared_ptr<my_src_type> pSrc(raw_ptr); dict[topic] = pSrc; } ``` Can I do it like this?

Original source