问题
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.
回答1:
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...
回答2:
The get member function returns the underling pointer and is fine to use with existing code as long as that code doesn't manage the memory you pass in.
来源:https://stackoverflow.com/questions/9908535/unique-ptr-with-an-api-that-expects-raw-pointers