unique_ptr upcast in return

Haix64 picture Haix64 · Aug 17, 2013 · Viewed 7.2k times · Source

I have this function that's supposed to generate different derived objs and return as a 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...();

      }
  }

there's no way I can get this thing going, even using the std::move. (Also used dynamic_cast, but maybe did it wrong).

This is the error I get: (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));

I hope I've been clear about what I wanna do.

How do I do it? Thanks.

Answer

Man of One Way picture Man of One Way · Apr 4, 2015

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...>();
  }
}