getting a normal ptr from shared_ptr?

C++BoostSmart PointersShared Ptr

C++ Problem Overview


I have something like shared_ptr<Type> t(makeSomething(), mem_fun(&Type::deleteMe)) I now need to call C styled function that requires a pointer to Type. How do I get it from shared_ptr?

C++ Solutions


Solution 1 - C++

Use the http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/shared_ptr.htm#get">`get()`</a> 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.

Solution 2 - C++

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.

Solution 3 - C++

For std::shared_ptr (C++11 onwards) also, there is a get method to obtain the raw pointer. link

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser34537View Question on Stackoverflow
Solution 1 - C++Adam RosenfieldView Answer on Stackoverflow
Solution 2 - C++Michael BurrView Answer on Stackoverflow
Solution 3 - C++cmpView Answer on Stackoverflow