unique_ptr与期望原始指针的API? [英] unique_ptr with an API that expects raw pointers?
问题描述
在使用托管内存和函数语言大约10年后,我终于回到了C ++,智能指针使我感到困惑。一半的文档仍然是关于弃用的 auto_ptr
。
我试图实现这个相当简单项目符号,但我要假装有一个原因...
After about 10 years of using managed memory and functional languages, I'm finally coming home to C++, and smart pointers are confusing the heck out of me. Half of the documentation out there is still regarding the deprecated auto_ptr
.
I'm trying to implement this fairly straightforward Bullet "hello world" program:
int _tmain(int argc, _TCHAR* argv[])
{
auto bp = unique_ptr<btBroadphaseInterface>(new btDbvtBroadphase);
auto cc = unique_ptr<btDefaultCollisionConfiguration>(new btDefaultCollisionConfiguration);
auto disp = unique_ptr<btDispatcher>(new btCollisionDispatcher(cc));
}
The btCollisionDispatcher
constructor wants a btCollisionConfiguration*
, but I'm giving it a unique_ptr
to one instead.
What do I normally want to do in this case? If there's a way to "de-smart" the pointer, something tells me that unique_ptr
isn't the right smart pointer to use.
C++ was my language of choice before I moved to other things. It's a little shocking coming back and seeing that all the patterns and practices have completely changed.
There is a get()
member function that gives you the raw pointer that is held by the unique_ptr
. This does not cause the unique_ptr
to relinquish the ownership, though, so proper cleanup will still happen (careful with storing that raw pointer!).
There is also a release()
member function, which relinquishes ownership. This means that you're back on dumb pointer land and cleanup is all your responsibility.
I can't fathom why the code is using new
in the first place and not just using automatic storage objects, but I'm going to pretend there is a reason...
这篇关于unique_ptr与期望原始指针的API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!