Unique_ptr upcast instead

I have this function, which should generate different derivatives of objs and return as unique_ptr<base> :

 class base {}; // contains pure functions. class derived1 {}; // reifies that pure iface. class derived2 {}; // reifies that pure iface. unique_ptr<base> factory::load(int param) { switch (param) { case PARAM_MAIN: return new derived1(); // return std::move(new derived1()); case PARAM_2: return new derived2(); case ...: return new derived...(); } } 

I cannot do this even using std :: move. (Also used dynamic_cast, but may have done it wrong).

This is the error I get: (gcc (GCC) 4.8.1 20130725 (preerelease) on ArchLinux)

 could not convert '(std::shared_ptr<base::model>((*(const std::shared_ptr<base::model>*)(& associatedModel))), (operator new(48ul), (<statement>, ((derived1*)<anonymous>))))' from 'derived1*' to 'std::unique_ptr<base>' associatedModel)); 

I hope I clearly understood what I want to do.

How should I do it? Thanks.

+4
source share
2 answers

You can either do unique_ptr<derived1>(new derived1()); , or even better (with C ++ 14) use std :: make_unique .

 using namespace std; class base {}; // contains pure functions. class derived1 {}; // reifies that pure iface. class derived2 {}; // reifies that pure iface. unique_ptr<base> factory::load(int param) { switch (param) { case PARAM_MAIN: return make_unique<derived1>(); case PARAM_2: return make_unique<derived2>(); case ...: return make_unique<derived...>(); } } 
+4
source

I solved it like this:

 return unique_ptr<base>(dynamic_cast<base*>(std::move( new derived1() ))); 

So the point is that it should be expanded to base while it is still raw, and only then wrapped in unique_ptr .

In any case, I appreciate the simpler answers. Especially these considerations are based on the unique_ptr internal functions and implementation.

-3
source

Source: https://habr.com/ru/post/1497567/


All Articles