Hi Guys,
I'm a game programmer enthusiast working on my own engine and I've been musing over using the standard library smart pointers in certain places in the engine. Generally, I prefer to use stack memory allocation for most things but I've found that certain aspects, such as the Vertex array in my Mesh class, are easier to allocate dynamically. For example, my Mesh class signature:
class Mesh
{
Vertex* m_pVerts;
string* m_pMeshObjectNames;
D3D11_PRIMITIVE_TOPOLOGY* m_pTopologies;
uint32_t* m_pReferenceCount;
uint32_t m_NumVerts;
bool m_HasNormalsDefined;
bool m_HasTexCoordsDefined;
void _LoadOBJMesh(LPSTR);
public:
Mesh();
Mesh(const Mesh&);
Mesh& operator=(const Mesh&);
~Mesh();
void LoadMesh(LPSTR, MeshType);
void LoadMeshAsync(LPSTR, MeshType);
};
The m_pMeshObjectNames and m_pTopologies are intended to point to dynamic arrays of their respective types however at the moment I haven't fully implemented that. Anyway my focus is the m_pVerts member. Originally, I implemented the pointer members of this class as std::shared_ptr<TYPE[]> and ran into the trouble using the [] partial specialization. I've also been wary of using the smart pointers in the standard library mostly due to lack of a full bodied understanding of how they work on my part. My implementation now handles the destruction of these dynamic members via reference counting. When I assign or use the copy constructor, the pointers are directly copied and then the reference counter is incremented. Finally, those members do not actually delete[] until the reference count has reached 0. Here is my destructor:
Mesh::~Mesh()
{
if (m_pReferenceCount && !--(*m_pReferenceCount))
{
if (m_pVerts)
{
delete[] m_pVerts;
m_pVerts = nullptr;
}
if (m_pMeshObjectNames)
{
delete[] m_pMeshObjectNames;
m_pMeshObjectNames = nullptr;
}
if (m_pTopologies)
{
delete[] m_pTopologies;
m_pTopologies = nullptr;
}
if (m_pReferenceCount)
{
delete m_pReferenceCount;
m_pReferenceCount = nullptr;
}
}
}
This code works as intended and I am pleased with it, however I don't know if it would be a widely accepted implementation. My question is: is this kind of code typically frowned upon in the industry? Do industry professionals normally like to use the standard library (or other respected library) smart pointers? I know these are probably very subjective questions, I just want some opinions!
Thanks!
Matt