C++ 从shared_ptr 得到一个普通的ptr?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/505143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:42:53  来源:igfitidea点击:

getting a normal ptr from shared_ptr?

c++boostsmart-pointersshared-ptr

提问by Adam Rosenfield

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?

我有类似的东西,shared_ptr<Type> t(makeSomething(), mem_fun(&Type::deleteMe))我现在需要调用需要指向Type. 我如何获得它shared_ptr

回答by Adam Rosenfield

Use the get()method:

使用get()方法:

boost::shared_ptr<foo> foo_ptr(new foo());
foo *raw_foo = foo_ptr.get();
c_library_function(raw_foo);

Make sure that your shared_ptrdoesn'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.

确保shared_ptr在库函数完成之前您没有超出范围 - 否则可能会导致糟糕的结果,因为库可能会在指针被删除后尝试对其进行处理。如果库函数在返回后维护原始指针的副本,则要特别小心。

回答by Michael Burr

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.

虽然我个人更喜欢使用该get()方法(它确实是正确的答案),但它的一个优点是它可以与重载operator*(指针取消引用)但不提供get()方法的其他类一起使用。例如,在泛型类模板中可能很有用。

回答by curiousmind

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

对于 std::shared_ptr(C++11 以后),也有一个 get 方法来获取原始指针。关联