Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unique_ptr upcast in return

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.

like image 544
Haix64 Avatar asked Aug 30 '26 10:08

Haix64


1 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...>();
  }
}
like image 169
Man of One Way Avatar answered Sep 04 '26 00:09

Man of One Way



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!