使用unique_ptr创建对象

Create object using unique_ptr

本文关键字:创建对象 ptr unique 使用      更新时间:2023-10-16

enum class了 3 种类型的对象。需要使用unique_ptr创建适当类型的对象。但是编译器会抛出很多错误。其中之一:invalid new-expression of abstract class type 'ObjectManager' { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }

也许我使用了错误的创建方法?

这是我的代码:

ObjectManager.h

class ObjectManager
{
public:
virtual void play(const std::string &sound) const = 0;
virtual void pause() const = 0;
virtual void stop() const = 0;
virtual void resume() const = 0;
};

对象类型.h

enum class ObjectType
{
type1,
type2,
type3
};

ObjectFactory.h

class ObjectFactory
{
private:
/* data */
public:
static unique_ptr<ObjectManager> create(ObjectType type);
};

对象工厂.cpp

static unique_ptr<ObjectManager> create(ObjectType type)
{
return make_unique<ObjectManager>(type);
}

主.cpp

auto createType = make_unique<ObjectManager>(ObjectType::type1);

我假设type1type2type3映射到派生自ObjectManager的类。我称它们为Manager1Manager2Manager3如下:

std::unique_ptr<ObjectManager> ObjectFactory::create(ObjectType type)
{
switch(type) {
case ObjectType::type1: return std::make_unique<Manager1>();
case ObjectType::type2: return std::make_unique<Manager2>();
case ObjectType::type3: return std::make_unique<Manager3>();
}
return nullptr; // or {} or throw a runtime_error
}

还应向基类添加virtual析构函数,否则基类指针上的delete将不会调用派生类的析构函数。

class ObjectManager {
public:
//...
virtual ~ObjectManager() = default;
//...
};

由于您有一个工厂类,因此您应该在main中使用它:

auto createType = ObjectFactory::create(ObjectType::type1);