Skip to content

Smart pointers

Ravi Mohan edited this page Dec 26, 2020 · 2 revisions

Pointers with default C++ memory management are called Smart Pointers. They come in three categories

  1. Unique pointers: Only one pointer can point to the object at a time. Memory is freed when pointer goes out of the scope.
  2. Shared pointers: Several pointers can point to the object and contribute towards reference counting (several owners). Memory is freed when reference count becomes 0.
  3. 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.


Unique pointer

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.


Shared pointer

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.


Clone this wiki locally