Hai*_*x64 3 polymorphism upcasting unique-ptr c++11
我有这个函数应该生成不同的派生对象并作为一个返回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...();
}
}
Run Code Online (Sandbox Code Playgroud)
即使使用 std::move,我也无法让这件事继续下去。(也使用了 dynamic_cast,但可能做错了)。
这是我得到的错误:(gcc (GCC) 4.8.1 20130725 (prerelease) 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));
Run Code Online (Sandbox Code Playgroud)
我希望我已经清楚我想做什么。
我该怎么做?谢谢。
您可以unique_ptr<derived1>(new derived1());使用std::make_unique做甚至更好(使用 C++14)。
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...>();
}
}
Run Code Online (Sandbox Code Playgroud)