Wednesday, 15 April 2015

c++ - "Downcasting" unique_ptr<Base> to unique_ptr<Derived> -


I have a series of several factories which unique_ptr < Base & gt; Under the hood, however, they have different derivative types, such as unique_ptr & lt; Derived & gt; , unique_ptr & lt; DeriveA & gt; , unique_print & lt; DerivedB & gt; etc.

Code given: Derived and Derived: Base We have:

  unique_ptr < Base & gt; DerivedAFactory () {Return Unique_Reference & lt; Base & gt; (New DeriveA); }  

Whatever I need to do is return to unique_ptr & lt; Base & gt; At some derivative level (essentially not the original internal one) from . To pseudo-code:

  unique_ptr  unique_ptr , then using a function that leaves the raw pointer and any other Code> re-assigns the unique taste of : 

  unique_ptr to the desired taste ( release  will be done explicitly by calling the caller) & Lt; Derived & gt; CastToDerived (Base * Obj) {Unique IPTR & Lt; Deleted & gt; (Static_cast & lt; Derivative * & gt; (OBJ)); }  

Is it legal, or is there something funky to do?


PS has an added complexity that some factories live in DLLs that are loaded dynamically in run-time, which means that I need to make sure That the finished products were destroyed in the same heap (space) because they were made. Transfer of ownership (which is usually in any other context) then a deliverter must be provided from the original context. But in addition to providing / delivering a delivery with the pointer, the casting problem should be the same.

I have some function templates, static_unique_ptr_cast and Dynamic_unique_ptr_cast Use them in earlier cases where you are absolutely certain that the indicator is actually a derived * , otherwise use later.

  template & lt; Typename derived, typename base, typename dell & gt; Std :: unique_ptr & lt; Derived, Del & gt; Static_unique_ptr_cast (std :: unique_ptr & lt; base, del & gt; & amp; amp; P) {autoD = static_account & lt; Derivative * & gt; (P.Relize ()); Return std :: unique_ptr & lt; Derived, Del & gt; (D, std :: move (p.get_deleter ())); } Template & lt; Typename derivative, typename base, typenamename & gt; Std :: unique_ptr & lt; Derived, Del & gt; Dynamic_unique_ptr_cast (std :: unique_ptr & lt; base, del & gt; & amp; amp; amp; amp; amp; amp; amp;; p;) (if (concluded * result = dynamic_costs & lt; generated * & gt; (p.get ()) {p .release (); Return std :: unique_ptr & lt; Derived, del & gt; (Results, std :: move (p.get_deleter ())); } Return std :: unique_ptr & lt; Derived, Del & gt; (Nullptr, p.get_deleter ()); }  

To get this work done, a rvalue is referencing that you get theft unique_ptr from below the foot of the collar was done.


No comments:

Post a Comment