-
-
Notifications
You must be signed in to change notification settings - Fork 0
Smart pointers
Pointers with default C++ memory management are called Smart Pointers. They come in three categories
- Unique pointers: Only one pointer can point to the object at a time. Memory is freed when pointer goes out of the scope.
- Shared pointers: Several pointers can point to the object and contribute towards reference counting (several owners). Memory is freed when reference count becomes 0.
- Weak pointers: Non-owning reference (reference count is not incremented). Memory can be freed even if the object is referenced by the weak pointer
In Karma we use smart pointers for the memory management. Few instances are noted below.
Here we define a unique pointer
std::unique_ptr<Window> m_Window;and set it to a single window here
m_Window = std::unique_ptr<Window>(Window::Create());Since we are sure that the ownership of the Window is retained by the Application for the entire lifetime of the program, our use of the unique pointer is justified.
In this code we have
std::shared_ptr<VertexBuffer> m_VertexBuffer;
m_VertexBuffer.reset(VertexBuffer::Create(vertices, sizeof(vertices)));where we declare a shared pointer m_VertexBuffer and instantiate a VertexBuffer object here
VertexBuffer* VertexBuffer::Create(float* vertices, uint32_t size)
{
switch (Renderer::GetAPI())
{
case RendererAPI::API::None:
KR_CORE_ASSERT(false, "RendererAPI::None is not supported");
return nullptr;
case RendererAPI::API::OpenGL:
return new OpenGLVertexBuffer(vertices, size);
}
KR_CORE_ASSERT(false, "Unknown RendererAPI specified");
return nullptr;
}Next this line transfers the ownership of the VertexBuffer object from Application to VertexArray.
m_VertexArray->AddVertexBuffer(m_VertexBuffer);where AddVertexBuffer is defined as (see here)
void OpenGLVertexArray::AddVertexBuffer(const std::shared_ptr<VertexBuffer>& vertexBuffer)
{
...
m_VertexBuffers.push_back(vertexBuffer);
}Since the ownership transfer is involved, our use of shared pointer is justified.