James
James

Reputation: 67

Using shared_ptr with an abject that is typedef from void*

I am running into some problems porting some code that uses smart pointers.

Old code..

shared_ptr<Foo> create_Foo();

Where Foo is internally created via a function

Foo* Foo::FooFactory;

So i understand that we are creating a Ptr to a C++ class/object and then passing that ptr to the shared Ptr object to create a shared ptr that holds a ptr to an object of the type Foo...

But what happens when i want to create a smart ptr to hold an object that is typdef'd as an object form a void*?

Eg.

typdef void* FOO_HANDLE
shared_ptr<FOO_HANDLE> create_foo();

With an internal factory func like

FOO_HANDLE FooFactory();

Basically i am confused about to declare and create the shared_ptr object with a the typedef FOO_HANDLE object, that is essentially a void*! Also because the FOO_HANDLE is a ptr to a C object it gets destroyed via a destroy method ala,

FooDestory(FOO_HANDLE);

So i guess i also need to tell the smart_prt about the method to destory the object.

I am starting to think that using smart ptrs here is the wrong approach.. but thought i would ask here first...

Upvotes: 1

Views: 173

Answers (1)

Brian Bi
Brian Bi

Reputation: 119219

A std::shared_ptr<void> can hold a void*. When you construct such a shared_ptr, you need to provide the deleter, which will be type-erased (and is hence not part of the shared_ptr type itself). You can do this:

shared_ptr<void> create_foo() {
    return {FooFactory(), FooDestroy};
}

Upvotes: 3

Related Questions