1

I'm trying to implement an efficient and error free way to perform downcasting of a unique_ptr<Base> to a derived class unique_ptr<Derived>. Reading some posts I found that something like this can work (simple dynamic_cast). However, in this other post they say that to perform the downcasting properly the deleter has to be extracted and reassigned.

I'd like to know when it is important to extract the deleter and how should I implement that, since in the answer the just provide the template function with the Del type, but I don't understand how to use this type in an actual implementation.

EDIT:

More specifically, I do not understand what exactly is the Del type and how to set it in an actual example. I understand that it is related to the deleter, but I don't know how to define and use it. Since this is not clear to me by only reading this, I'd like some more explanation.

Community
  • 1
  • 1
gcswoosh
  • 1,279
  • 1
  • 15
  • 31
  • 3
    The second answer you've mentioned provides a complete and working solution. So what is your question? If you don't understand how a specific part of that solution works, please explain what you understand and what not. – 5gon12eder Mar 16 '15 at 13:50
  • Indeed I wrote that I did not understand what is the Del type and how to use it in an actual example – gcswoosh Mar 16 '15 at 13:54
  • `Del` is the type of the deleter. Note that (unlike with `std::shared_ptr`) the deleter type is part of the `std::unique_ptr`'s type. By “how to use it in an actual example”, do you mean that you don't know how to *call* that function? Because it is complete as written. – 5gon12eder Mar 16 '15 at 14:03
  • I mean when calling that function I have to define also the `Del` type. Where do I get it? is there a method of the `unique_ptr` that returns it? – gcswoosh Mar 16 '15 at 14:07
  • 1
    As I've said, it's part of the type. The compiler will be able to deduce it if you call the function like in `dynamic_pointer_cast(std::move(pointer))`. – 5gon12eder Mar 16 '15 at 14:18
  • 1
    @Gabrielecswoosh: You don't need to specify `Base` or `Del`, they can be deduced from the function argument. `auto derived_ptr = static_unique_ptr_cast(std::move(base_ptr));` should do the job. – Mike Seymour Mar 16 '15 at 14:20
  • Ok thanks, I didn't understand that, now it makes sense. – gcswoosh Mar 16 '15 at 14:20

0 Answers0