Prismatic
Prismatic

Reputation: 3348

How do I properly convert between unique_ptr<T> and unique_ptr<void>?

I have a scenario where I want to move from unique_ptr(T) to unique_ptr(void), then possibly back to unique_ptr(T)

unique_ptr(void) requires a deleter:

unique_ptr<T> uptr_custom;
uptr_custom.reset(new T(...));

// T -> void
unique_ptr<void,void(*)(void*)> uptr_void(
    uptr_custom.release(),
    [](void * data) { delete static_cast<T*>(data); });

// void -> T
// ?

My questions are:

Is the move from unique_ptr(T) --> uniqe_ptr(void) correct?

How can I go from unique_ptr(void) back to unique_ptr(T) such that unique_ptr(T) no longer has a custom deleter?

Upvotes: 0

Views: 155

Answers (1)

Igor Tandetnik
Igor Tandetnik

Reputation: 52471

unique_ptr<T> p;
p.reset(static_cast<T*>(uptr_void.release()));

Upvotes: 2

Related Questions