c++ - How can I return unique_ptr from factory method? -
i have few classes heroes extended abstract class warrior:
enum warrior_id { infantryman_id=0, archer_id, horseman_id }; class warrior { public: virtual void info() = 0; virtual ~warrior() { } static unique_ptr<warrior> createwarrior( warrior_id id ); }; class infantryman: public warrior { public: void info() { cout << "infantryman" << endl; } }; class archer: public warrior { public: void info() { cout << "archer" << endl; } }; class horseman: public warrior { public: void info() { cout << "horseman" << endl; } };
and factory method, returns specific character:
unique_ptr<warrior> warrior::createwarrior( warrior_id id ) { unique_ptr<warrior> p; switch (id) { case infantryman_id: p = new infantryman(); //this doesn't work break; case archer_id: p = new archer(); //this doesn't work break; case horseman_id: p = new horseman(); //this doesn't work break; default: } return p; };
how can return unique_ptr specific character without using make_unique ?
std::unique_ptr
's pointer constructor explicit, need
p = std::unique_ptr<warrior>{new infantryman()};
alternatively, use reset()
member function:
p.reset(new infantryman());
as noted in comments, don't need declare local variable p
, modify it. can return directly switch block:
case infantryman_id: return std::unique)ptr<warrior>{new infantryman{}}; case archer_id: return std::unique)ptr<warrior>{new archer{}};
and on.
Comments
Post a Comment