i have something like shared_ptr t(makeSomething(), mem_fun(&Type::deleteMe)) i now need to call C styled func that require a pointer to Type. How do i get it from shared_ptr?
+12
A:
Use the get()
method:
boost::shared_ptr<foo> foo_ptr(new foo());
foo *raw_foo = foo_ptr.get();
c_library_function(raw_foo);
Make sure that your shared_ptr
doesn't go out of scope before the library function is done with it -- otherwise badness could result, since the library may try to do something with the pointer after it's been deleted. Be especially careful if the library function maintains a copy of the raw pointer after it returns.
Adam Rosenfield
2009-02-02 22:04:50
you should perhaps note something about the shared_ptr going out of scope before the c_library_function has done its thing with the raw_foo.
roe
2009-02-02 22:06:19
roe: i know about that, i just needed to know about get :).Thanks Adam! :D
acidzombie24
2009-02-02 22:07:34
+2
A:
Another way to do it would be to use a combination of the &
and *
operators:
boost::shared_ptr<foo> foo_ptr(new foo());
c_library_function( &*foo_ptr);
While personally I'd prefer to use the get()
method (it's really the right answer), one advantage that this has is that it can be used with other classes that overload operator*
(pointer dereference), but do not provide a get()
method. Might be useful in generic class template, for example.
Michael Burr
2009-02-02 22:41:11
@acidzombie24 - I'm not sure why you like this better. The Get() method is better to use in probably 99% or more of the cases.
Michael Burr
2009-02-03 08:43:47
i'm using get but i still like this answer. mostly bc it recommends both what to do and NOT to do.
acidzombie24
2009-02-03 17:43:49