【发布时间】:2022-01-25 23:50:24
【问题描述】:
我有一个带有私有构造函数和公共 CreateEntity 函数的 Entity 类。 CreateEntity 堆栈分配新实体。在我的应用程序中,我想使用指向返回实体的唯一指针。我找到了一个带有临时唯一指针和两个移动指令的解决方案。 如何使用 make_unique 和单个移动指令在 Start() 中编写两行?
class Entity
{
public:
Entity(const Entity&) = delete;
Entity& operator=(const Entity&) = delete;
Entity(Entity&&) = default;
Entity& operator=(Entity&&) = default;
static Entity CreateEntity();
private:
Entity(id_t id): m_ID(id) {}
private:
uint32_t m_ID;
};
Entity Entity::CreateEntity()
{
static id_t currentID = 0;
return Entity{currentID++};
}
struct Lucre : public Application
{
bool Start();
std::unique_ptr<Entity> m_Object;
}
bool Lucre::Start()
{
std::unique_ptr<Entity> ptr( new Entity(std::move(Entity::CreateEntity())));
m_Object = std::move(ptr);
}
【问题讨论】:
-
我不确定我是否理解,但是没有 move 指令。
Start()方法看起来有点到处都是。它的目的是什么,从上到下... 1. 做什么,做什么? ... -
公开你的默认构造函数,不接收参数,在
: m_ID{currentID++}使用成员初始化,currentID是一个静态成员,然后用m_Object = std::make_unique<Entity>();初始化唯一指针。 -
Ted,有一个错字现已修正。在我的代码中,它被称为 m_CameraObject。当我简化 StackOverflow 的代码时,我忽略了一个事件。 Rturrado,这是一个很好的替代方法,我将来可能会使用它。非常感谢!
标签: c++ move unique-ptr