Shared Pointers - Karclan/Games-Programming-Engine GitHub Wiki

Smart pointers can be used to create pointers with automated memory management (garbage collection etc). They sacrifice a bit of performance in exchange for being safer. Shared pointers are one form of smart pointer. They share ownership of the memory, meaning that the object created on the heap will remain there until all shared pointers to it go out of scope. It will then be automatically deleted. By passing components around as shared pointers, we can send them to different subsystems (rendering, physics etc) without worrying about clearing up the memory afterwards.

###Creating a Shared Pointer

The following code creates shared pointer to a component with the default constructor, meaning it is set to null. std::shared_ptr myPointer;

You can check to see if a shared pointer is pointing to null with any of the following

myPointer == nullptr;   // compare to nullptr
myPointer == NULL;      // compare to NULL
!myPointer;             // simply use as a bool. False == null

To create an object on the heap and link it to a shared pointer, pass "new Object" as the argument.

myPointer = std::shared_ptr<Component>(new Camera()); // new Camera component stored in a pointer to a component

###Use of Typedefs Because components and other classes are passed around in the engine as shared pointers so frequently, it becomes a chore typing out std::shared_ptr every time. Typedefs have been used to define shared pointers, usually at the bottom of the header the relate to. E.g in component.h

typedef std::shared_ptr<Component> SPtr_Component;

This defines SPtr_Component to be a shared pointer to a component. All shared pointers follow the same pattern, e.g SPtr_Camera is a shared pointer to a camera.

###General Use Use shared pointers exactly as you would regular pointers, e.g

myPointer->DoStuff();

To change what the pointer is pointing to or to set it to null, use the reset function. This has the same params as the constructor.

myPointer->reset(new SPtr_Camera);

###Casting There are specific functions for pointer casts in the STL. Rather than static_cast you need to use static_pointer_cast etc. The following code casts myPointer to a shared pointer to a Camera.

std::static_pointer_cast<Camera>(myPointer);
⚠️ **GitHub.com Fallback** ⚠️