getting a normal ptr from shared_ptr?

我们两清 提交于 2019-11-30 04:11:28

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!