我试图找到一个界面的工作模式。
我在做什么的一些信息。我在 dx11 中实现了一个渲染引擎。我的目标是提供一个简单且高度接口的引擎,其中客户端不必具备任何 dx11 或高级渲染技术的知识。
我有我的引擎,该引擎提供了设置和创建任何对象、地形、太阳、照明、水、地平线和和和的功能。
现在我来回答我的问题。我所谓的引擎MeshController提供了这3个方法(代码被简化):
//check if that description already exists (if not create it) and return that id
UINT addDesc(const MESH_ENTITY_DESC& desc);
//create an instance of the given object
MeshEntity* createInstance(const UINT descID);
//destroy the instance
void destroyInstance(MeshEntity* entity);
为了避免客户端处理指针,我尝试将其打包在一个包装类中,该类将执行 nullptr 检查,检查实体是否已被销毁或已创建等等。
包装:
class MeshObject
{
private:
UINT g_Desc;
MeshEntity* g_Entity;
}
现在我希望对象始终处于有效状态。如果实例在丢失包装对象之前没有被销毁,它会造成内存泄漏(不是真的,但是我的控制器会渲染它直到场景关闭,或者会阻塞一个实例槽,总而言之,客户端将失去对实例)。所以我的第一个想法是这样的:
//constructor
MeshObject(const MESH_ENTITY_DESC& desc)
{
g_Desc = Controller::addDesc(desc);
g_Entity = Controller::createInstance(g_Desc);
}
//copy constructor
MeshObject(const MeshObject& mo)
{
g_Desc = mo.g_Desc; //no need of adding desc, already exists
g_Entity = g_Entity; // no need of recreation? or should i also create a copy of the rendered object in the controller, so duplicate it?
}
MeshObject& operator=(const MeshObject& mo)
{
g_Desc = mo.g_Desc; //no need of adding desc, already exists
g_Entity = g_Entity; // definitly no need of recreation
}
~MeshObject()
{
Controller::destroyInstance(g_Entity);
}
由于三规则,我需要复制和赋值运算符。但是问题就来了。createInstance 和 destroyInstance 方法有很多开销,因为在场景中添加/删除,可能会重新创建渲染缓冲区......
所以现在我尝试找到任何方法来防止对象被破坏,如果它之前被复制过,或者如果它有一个有效的引用(指针)。这不是典型的动态内存分配,而是我的控制器中的某种分配。
客户端的典型用例:
std::vector<MeshObject> moVector;
for(int i = 0; i < blabla; i++)
{
MeshObject mo(someDescription); // created object in controller
//do lot of init stuff, like position, rotation, ...
mo.pushback(mo); // here mo will be copied, try to avoid double creation
} // here mo will lose scope and will be destroyed, stop destroying because there is a valid wrapper object
谢谢你的帮助!